说明
上一章将自己学习 netty 的Demo放了上去.
这里我们对照着代码分析一下 Netty 背后的东西
服务端
EventNioLoopGroup 时服务端和客户端的本质.
用来使用在客户端和服务端通信
用在服务端,接收客户端的消息.进行事件的处理.
NioEventLoopGroup
BossGroup 和 WorkerGroup:是俩个线程组.
都含有子线程(NioEventLoop)的个数
默认是以 CPU 的核数 * 2
如果 NioEventLoopGroup 的参数为0(不填默认为0)时,
会有一个默认值:
SystemPropertiesUtil.getInt("io.netty.eventLoopThreads"xxx)
CPU 核数 * 2
验证
@Test
public void run(){
System.out.println(NettyRuntime.availableProcessors());
}
输出
22:42:33.831 [main] DEBUG io.netty.util.internal.logging.InternalLoggerFactory - Using SLF4J as the default logging framework
8
指定NioEventLoopGroup的个数
指定
boss或worker不一定指定那么多的线程数目
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
默认
在默认的情况下,BossGroup有 CPU 核数 * 2 的 线程组.
每次来一个客户端连接,分配给NioEventLoop.用来处理该客户端的连接.
NioEventLoop
每一个NioEventLoop 包含一个
selector(实际类型:SelectedSelectionKeySetSelector)
taskQueue,executor(ThreadFactory生成的)
readOnlyChildren:... ...
等待读写事件,如果有数据到来,获得该NIO对应的Handler进行处理
ctx:(Default)ChannelHandlerContext
包含:
Handler:自己实现的Handler
pipeline:DefaultChannelPipeline
channel:NioSockerChannel
EventLoop:pipeline属于那个线程的
inboud:boolean 类型.true:入栈的状态
pipeline:双向链表
pipeLine:
channel:NioSockerChannel
PipeLine包含Channel Channel包含PipeLine CTX包含PipeLine和Channel
总结
BossGorup和WorkerGroup本质归属同意类型.用于不同的作用
本质为NioEventLoopGroup();而NioEvetnLoopGroup本质为一个线程组.
包含多个线程.
每个线程为一个NioEventLoop,包含有自己的selector,taskQueue.Handler.
而重写的Handler read方法的 参数为 ChannelHandlerContext,包含了channel和pipeLine.
... ...