Netty是什么
Netty is an asynchronous event-driven network application framework
for rapid development of maintainable high performance protocol servers & clients
异步、基于事件驱动,使用简单易维护、高性能
目前在基于java体系的网络框架中业界排名第一 (其他诸如grizzly,mina),并且被使用在很多中间件系统和业务系统中。
![](https://img.haomeiwen.com/i9891589/4db3da7a805caa87.png)
Netty的优势
-
高性能
堆外内存池,本地native增强,异步编程,lockfree思想,代码细节优化如按位操作 -
异步
除了通讯本身异步,框架内部也使用大量的异步处理,EventLoop尽可能不执行阻塞的操作,主要通过ChannelFuture, ChannelPromise来实现 -
功能丰富
多协议支持TCP, UDP, SCTP, HTTP, HTTP2, WEBSOCKET, MQTT, 丰富的CODEC编解码,粘包拆包工具,SSLHandler等 -
使用简单
上层API简单友好,解耦网络底层和业务逻辑的处理。业务层一般只需使用引导类,把自定义的Handler和Netty提供的各种通用Handler加入到ChannelPipeline链上 -
编程模型统一
无论是常用的bio, nio模式还是native模式,切换只需几行代码就行 -
修复或兼容Jdk本身的bug
修复Jdk中epoll空转的问题,部分tcp参数不支持的兼容处理等
Reactor模型
1. 单线程版本
![](https://img.haomeiwen.com/i9891589/fd5e63934d524e8f.png)
注: 全部由一个Reactor单线程完成所有的操作,包括accept, read, decode, compute, encode, send。不能重复发挥多核CPU的优势
2.多线程版本
![](https://img.haomeiwen.com/i9891589/daea8b08872aa368.png)
注: Reactor线程还是一个,但是只做accept, read, send。其他耗时处理decode, compute, encode通过queue的方式交给work threads线程池执行
3.主从Reactor模式
![](https://img.haomeiwen.com/i9891589/9da127911a7dbc56.png)
最经典的 1 + N + M的模式, 把Reactor线程又细分成了1个主Reactor和N个从Reactor
其中主Reactor专门负责accept, 从Reactor有多个,一般设置成CPU核数,只做read和send
耗时处理decode, compute, encode不变,由从Reactor通过queue的方式交给work threads线程池执行
4.Netty中的Reactor模式
![](https://img.haomeiwen.com/i9891589/d93344fcd8428fda.png)
NioEventLoop的职责其实就是Reactor线程的职责
但是又额外增加了非IO事件的处理,既会做3个事情
select检测是否有就绪IO事件
processSelectKeys处理IO事件
runAllTasks处理非IO任务
Netty中事件类型更加丰富
如Active,InActive,Read,Write,Exception,UserEvent等
Netty中常用的线程池有两种方式
BossGroup + WorkerGroup
其中BossGroup对应主Reactor
WorkerGroup对应从Reactor + work threads
(或者也可以在Handler中自定义线程池)
BossGroup + WorkerGroup + DefaultEventLoopGroup
其中BossGroup对应主Reactor
WorkerGroup对应从Reactor
DefaultEventLoopGroup对应work threads
pipeline机制
Netty的ChannelPipeline采用职责链模式,本质上是一个双向链表,当Channel上发生一个事件的时候,由Pipeline的一端经过各个HandlerContext, 处理后最终到达另外一端
netty中处理的事件分inbound和outbound类型,inbound事件流转方向从Head到Tail,outbound事件流转方向是从Tail到Head
![](https://img.haomeiwen.com/i9891589/ec0a42b32ceba51c.png)
//inbound事件
ChannelHandlerContext.fireChannelRegistered()
ChannelHandlerContext.fireChannelActive()
ChannelHandlerContext.fireChannelRead()
ChannelHandlerContext.fireChannelReadComplete()
ChannelHandlerContext.fireExceptionCaught()
ChannelHandlerContext.fireUserEventTriggered()
ChannelHandlerContext.fireChannelWritabilityChanged()
ChannelHandlerContext.fireChannelInactive()
ChannelHandlerContext.fireChannelUnregistered()
//outbound事件
ChannelHandlerContext.bind()
ChannelHandlerContext.connect()
ChannelHandlerContext.write()
ChannelHandlerContext.flush()
ChannelHandlerContext.read()
ChannelHandlerContext.disconnect()
ChannelHandlerContext.close()
ChannelHandlerContext.deregister()
//注意一个细节点
ChannelHandlerContext.channel().write() //从TailContext往后开始处理
ChannelHandlerContext.write() //从当前Context开始往后处理
网友评论