java - Netty 中 ChannelInitializer 相对于 Channel Handler 的优势

标签 java netty nio channel

与直接使用 ChannelHandler 链相比,使用 ChannelInitializer 有什么优势?

例如,我可以使用服务器 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)

The handler specified here will always be evaluated by a newly accepted Channel. The ChannelInitializer is a special handler that is purposed to help a user configure a new Channel. It is most likely that you want to configure the ChannelPipeline of the new Channel by adding some handlers such as DiscardServerHandler to implement your network application. As the application gets complicated, it is likely that you will add more handlers to the pipeline and extract this anonymous class into a top level class eventually.

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

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

关于java - Netty 中 ChannelInitializer 相对于 Channel Handler 的优势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28189380/

相关文章:

java - Android 实现可滑动的选项卡式布局

exception-handling - 为什么 ChannelOutboundHandler 异常没有被 exceptionCaught() 方法捕获? (Netty 4.0.4.Final)

java - org.jboss.msc.service.StartException 服务 jboss.web.deployment.default-host./: Failed to start service

Java 方法按值传递问题

java - Netty ByteBuf处理,管道中的解码器结构

java - 带有 Netty 和 WebFlux 的 ChannelOperation 终端堆栈

java - 如何读取socket中的大数据并写入socketchannel

java - 为什么我的 Spring webflux 应用程序在每个请求上都会生成临时文件?

java - 什么情况下 eventloop.inEventLoop() == false ?

java - 根据特殊的非空格空白字符进行拆分