简体   繁体   中英

Netty do-nothing codec for IO?

I'm writing http-server which is going to perform some very heavy computations. I have some encoder-decoder pipeline related to business logic and blocking 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())
}

So I decided to create another worker

EventLoopGroup ioGroup = new NioEventLoopGroup(4)

And add simple handler in the very beginning:

.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())

Is it commmon to do like this in Netty? Or there is a better approach?

Usually you would just not specify the executorGroup when adding a handler to the pipeline if you want to run it on the IO thread. My suggestion would be to structure the pipeline this:

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());
}

This will have your MyBusinessLogic run in another thread and not block the IO thread. If you the ResponseBodyDecoder is also very heavy on the cpu / or block you can also use the executorGroup here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM