Netty线程EventLoop

学习目标

NioEventLoopGroup与Reactor模式对应 NioEventLoop run方法重要三件事 Selector SelectionKeySet 的优化 如何解决select空轮询导致cpu100%? bossGroup为什么会设置多线程?

NioEventLoopGroup与Reactor模式对应

单线程模式-示例

EventLoopGroup bossGroup = new NioEventLoopGroup(1);
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup);
// 或者这么配置
// b.group(bossGroup,bossGroup);

多线程模式-示例

// 处理非IO操作的线程池
final EventLoopGroup noIOThreadPool = new DefaultEventLoopGroup(5,new DefaultThreadFactory("noIOThreadPool"));

// 处理IO操作的线程池
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup);
b.childHandler(new ChannelInitializer<SocketChannel>() {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        //handler指定非IO线程池处理
        ch.pipeline().addLast(noIOThreadPool,new InBoundHandler());
    }
})

主从线程模式-示例

// 处理非IO操作的线程池
final EventLoopGroup noIOThreadPool = new DefaultEventLoopGroup(5,new DefaultThreadFactory("noIOThreadPool"));

// 处理IO操作的线程池
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workGroup = new NioEventLoopGroup(4);
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup,workGroup);
b.childHandler(new ChannelInitializer<SocketChannel>() {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        //handler指定非IO线程池处理
        ch.pipeline().addLast(noIOThreadPool,new InBoundHandler());
    }
})

NioEventLoop run方法重要三件事

results matching ""

    No results matching ""