Netty源码分析系列--1.NioEventLoopGroup

Netty服务器开发模式

public class MyServer {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new MyServerInitializer());

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

        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
  • 创建两个事件循环组EventLoopGroup,即bossGroupworkerGroup

  • bossGroup接收事件后,转发给workerGroup

NioEventLoopGroup

  • 构造函数如下:bossGroup的线程数通常指定为1
public NioEventLoopGroup() {
    this(0);
}

//指定线程个数
public NioEventLoopGroup(int nThreads) {
    this(nThreads, (Executor) null);
}
  • NioEventLoopGroup实现了 EventLoopGroup接口, EventLoopGroup文档说明:

    // 提供将Channel可以注册到EventLoopGroup中的若干方法
    public interface EventLoopGroup extends EventExecutorGroup {
        //返回下一个即将被使用的EventLoop
        @Override
        EventLoop next();
    
        //将Channel注册到EventLoop中,注册完成后,返回的ChannelFuture对象会得到通知
        ChannelFuture register(Channel channel);
    
        //传入的ChannelPromise对象在注册完成后也会得到通知
        ChannelFuture register(ChannelPromise promise);
    }
    

    ChannelPromise接口继承了ChannelFuture接口。

  • 构造函数中的其他参数的默认值:
  1. selectorProvider: SelectorProvider.provider()
  2. selectStrategyFactory:DefaultSelectStrategyFactory.INSTANCE
  3. rejectedExecutionHandler:RejectedExecutionHandlers.reject()
  • NioEventLoopGroup的父类MultithreadEventLoopGroup:

    ​ 当传入的nThreads线程数为0时,会使用默认线程数字段DEFAULT_EVENT_LOOP_THREADS,它的计算逻辑如下:

    public abstract class MultithreadEventLoopGroup extends MultithreadEventExecutorGroup implements EventLoopGroup {
    
        private static final int DEFAULT_EVENT_LOOP_THREADS;
    
        static {
            DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(
                    "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));
        }
    
      
        protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args) {
            super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args);
        }
    }
    

你可能感兴趣的:(Netty源码分析系列--1.NioEventLoopGroup)