用于IO的Netty do-nothing编解码器?

时间:2017-11-24 07:11:56

标签: java io netty

我正在编写http-server,它将执行一些非常繁重的计算。我有一些与业务逻辑和阻塞IO相关的编码器 - 解码器管道。

public void initChannel(Channel ch) { 
    ch.pipeline()
         //All actions in these handlers are very heavy and involve some IO
        .addLast(logicGroup, new HttpRequestDecoder())
        .addLast(logicGroup, new HttpObjectAggregator(Int.MaxValue))
        .addLast(logicGroup, new HttpResponseEncoder())
        .addLast(logicGroup, new ChunkedWriteHandler())
        .addLast(logicGroup, new ResponseBodyDecoder())
        .addLast(logicGroup, new MyBusinessLogic())
}

所以我决定创建另一个工作者

EventLoopGroup ioGroup = new NioEventLoopGroup(4)

并在最开始添加简单的处理程序:

.addLast(ioGroup, new ChannelDuplexHandler()) //<---- Only for IO
.addLast(logicGroup, new HttpRequestDecoder())
.addLast(logicGroup, new HttpObjectAggregator(Int.MaxValue))
.addLast(logicGroup, new HttpResponseEncoder())
.addLast(logicGroup, new ChunkedWriteHandler())
.addLast(logicGroup, new ResponseBodyDecoder())
.addLast(logicGroup, new MyBusinessLogic())

通常在Netty中这样做吗?还是有更好的方法?

1 个答案:

答案 0 :(得分:2)

如果要在IO线程上运行处理程序,通常在向管道添加处理程序时不会指定executorGroup。我的建议是构建管道:

EventExecutorGroup executorGroup = new DefaultEventExecutorGroup(numberOfThreads);

...

public void initChannel(Channel ch) { 
    ch.pipeline()
      .addLast(new HttpRequestDecoder())
      .addLast(new HttpObjectAggregator(Int.MaxValue))
      .addLast(new HttpResponseEncoder())
      .addLast(new ChunkedWriteHandler())
      .addLast(new ResponseBodyDecoder())
      .addLast(executorGroup, new MyBusinessLogic());
}

这将使您的MyBusinessLogic在另一个线程中运行,而不是阻止IO线程。如果ResponseBodyDecoder对cpu /或块也很重,你也可以在这里使用executorGroup