How to execute business logic handler in a separate thread pool using netty

老子叫甜甜 提交于 2019-12-06 09:35:57

In case your goal is not to block IO event loop - you did it right. But due to netty specific, your handler will be always attached to the same thread of EventExecutorGroup and thus behavior you described above is expected.

In case you want to execute blocking operation in parallel as soon as it arrives you need to use the another way - separate ThreadPoolExecutor. Like this:

ch.pipeline().addLast(new ServerHandler(blockingThreadPool));

where blockingThreadPool is regular ThreadPoolExecutor.

For example:

ExecutorService blockingThreadPool = Executors.newFixedThreadPool(10);

Now, within your logic handler you can submit blocking tasks to this executor like this:

protected void channelRead0(ChannelHandlerContext ctx, Command cmd) throws Exception {

    blockingIOProcessor.execute(new Runnable() {
        @Override
        public void run() {
            System.out.println("Starting.");

            try {
                Thread.currentThread().sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            System.out.println("Finished.");
        }
    });

}

You can also pass context to this runnable in order to return the response back when processing is finished if needed.

Because the Netty handle the request which is sended from same socket by the same EventExecutor,so you can start more than one client,and see the result.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!