netty之NioEventLoopGroup源码解析

netty之NioEventLoopGroup源码解析

通过视频学习netty课程也有一段时间了,通过视频讲解的代码分析方式,自己也依葫芦画瓢尝试来一下子。

服务端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();

try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new MyServerInitializor());

ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
channelFuture.channel().closeFuture().sync();

} catch (Exception e) {
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}

代码解读

在代码的2、3行种,声明了两个事件循环组(NioEventLoopGroup),一个bossGroup,一个workerGroup。它们的作用分别是:bossGroup 是服务端用了接收客户端连接的事件循环组,workergroup是用于处理客户端请求的事件循环组;

NioEventLoopGroup

类图

从类图的继承关系来看出,NioEventLoopGroup的顶层父类是Executor。由此可知,NioEventLoopGroup也是基于多线程来实现的。现在来看看它的具体实现。

####NioEventLoopGroup 的初始化过程

  1. 调用它的无参构造方法

    1
    2
    3
    4
    5
    6
    7
    8
     /**
    // 创建一个使用默认线程数的实例(通过默认的ThreadFactory创建)
    * Create a new instance using the default number of threads, the default {@link ThreadFactory} and
    * the {@link SelectorProvider} which is returned by {@link SelectorProvider#provider()}.
    */
    public NioEventLoopGroup() {
    this(0);
    }
    1
    2
    3
    4
    5
    6
    7
    /**
    * Create a new instance using the specified number of threads, {@link ThreadFactory} and the
    * {@link SelectorProvider} which is returned by {@link SelectorProvider#provider()}.
    */
    public NioEventLoopGroup(int nThreads) {
    this(nThreads, (Executor) null);
    }