worker Group vs handler Thread in Netty

2019-08-24 21:36发布

I am setting up a Netty Server to accept multiple incoming client connections which will in turn do some processing, but confused about the wroker thread group vs Handler threads

I have tried assigning 10 worker threads and 20 handler threads as below.

EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup(10);
EventExecutorGroup handlerThread = new DefaultEventExecutorGroup(20);

try {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup);
    serverBootstrap.channel(NioServerSocketChannel.class);
    serverBootstrap.localAddress(new 
    InetSocketAddress(hostName,Integer.parseInt(port)));

    // initialize a new child handler for incoming request
    logger.debug("Incoming request from TCP client...assigning a new Server Handler");
    serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
    protected void initChannel(SocketChannel socketChannel) throws Exception 
    {
    socketChannel.pipeline().addLast(handlerThread,new NettyServerHandler());
                }
            });
            ChannelFuture channelFuture = serverBootstrap.bind().sync();
            channelFuture.channel().closeFuture().sync();

        } catch (Exception e) {
            logger.error("Unable to initialize TCP Server");
        } 

I cannot understand the difference between worker group's task and creating a new server handler. As per my understanding, the handler thread pool will be assigned to each instance of NettyServerHandler. But then what is the role of creating worker group pool of 10 threads?

标签: netty
1条回答
看我几分像从前
2楼-- · 2019-08-24 22:16

You don't have to make an EventLoopGroup with 10 threads for accepting 10 clients. Its enough to pass one thread on the bossGroup and none on the workerGroup:

EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();

Make sure the ServerBootstrap().childOption(ChannelOption.SO_BACKLOG, 10); is set to at least 10 for accepting 10 clients.

So the role of the EventLoopGroup is accepting the clients as far as i know. The ServerHandler on the other hand is there to receive the data and manage what to do with it, and you can intercept if someone joined or if there is any problem with the connection by overriding the ChannelHandlerAdapter methods.

I hope i understood your problem and helped you to understand it,

kind regards

查看更多
登录 后发表回答