我正在编写超文本传输协议-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())
在内蒂这样做是不是很通俗?还是有更好的方法?
通常,如果要在 IO 线程上运行处理程序,则在向管道添加处理程序时,您不会指定执行器组。我的建议是将管道构建为:
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 线程。如果你的响应体解码器
在cpu/或块上也非常重,你也可以在这里使用执行器组
。