How can you safely perform blocking operations in a Netty channel handler?

后端 未结 1 656
清酒与你
清酒与你 2021-02-15 16:43

I\'m building a small Netty-based application that performs I/O operations across a socket connections (i.e. telnet/ssh). I am starting up my socket server with Netty\'s

相关标签:
1条回答
  • 2021-02-15 17:31

    If an operation in Netty takes longer time to complete or is blocking it is advisable to perform that in a handler that uses a separate ExecutorGroup so that the main EventLoop thread is not blocked.

    You can specify that during the pipeline creation.

    Quoting an example that uses executor group for DB operation from ChannelPipeline javadoc

    static final EventExecutorGroup group = new DefaultEventExecutorGroup(16);
     ...
    
     ChannelPipeline pipeline = ch.pipeline();
    
     pipeline.addLast("decoder", new MyProtocolDecoder());
     pipeline.addLast("encoder", new MyProtocolEncoder());
    
     // Tell the pipeline to run MyBusinessLogicHandler's event handler methods
     // in a different thread than an I/O thread so that the I/O thread is not blocked by
     // a time-consuming task.
     // If your business logic is fully asynchronous or finished very quickly, you don't
     // need to specify a group.
     pipeline.addLast(group, "handler", new MyBusinessLogicHandler());
    
    0 讨论(0)
提交回复
热议问题