直接使用ChannelInitializer而不是使用ChannelHandlers链有什么优势?

例如,使用服务器 bootstrap ,我可以执行以下操作:

bootstrap.childHandler(channel_handler);

添加在channel_handler的实现中,我将实现以下内容
class simple_channel_handler implements ChannelHandler
{
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("handler added");
        ctx.pipeline().addLast(new simple_channel_handler_2());
    }
}

就像ChannelInitializer一样
        ch.pipeline().addLast(
                               new channel_handler_1(),
                               new channel_handler_2()
                             );

在每个处理程序中,我都可以做
class channel_handler_1 extends ChannelInboundHandlerAdapter
{

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("Channel just became active");
        ctx.fireChannelRead(ctx); // Fire directly to channel handler 2
    }
}

那么, channel 处理程序不必了解将 channel 读取到的位置的唯一好处是吗?我看不到使用 channel 初始化程序的任何其他优势

最佳答案

根据文档(请参见http://netty.io/wiki/user-guide-for-4.x.html)



因此,ChannelInitializer是一种根据需要添加处理程序的干净方法,尤其是如果您有多个处理程序时。

它不会阻止一个处理程序添加更多处理程序(如您在第一个示例中所做的那样),例如,根据上下文在管道中动态添加/删除一个处理程序,而是针对“静态”或“默认”一系列处理程序,所以使用ChannelInitializer是一种更简洁的方法,因为它确实很接近 bootstrap 定义,因此更具可读性。

10-05 22:55