4

我正在 Netty 4 中尝试自定义出站消息处理程序,但似乎无法使其正常工作。处理程序只记录一个语句并添加到通道管道的底部。我的理解是,一旦发出写入操作,就会按顺序从下到上调用这些处理程序。自定义处理程序的想法是它将在任何其他出站消息处理程序之前执行。

不幸的是,当我将此日志处理程序添加到管道时,我看到了日志语句,但 Netty 似乎立即关闭了连接。这是我的通道初始化程序和出站处理程序代码。

HttpOutboundHandler.java

public class HttpOutboundHandler extends ChannelOutboundMessageHandlerAdapter<DefaultFullHttpResponse> {
    private static final Logger logger = LoggerFactory.getLogger(HttpOutboundHandler.class);

    @Override
    public void flush(ChannelHandlerContext context, DefaultFullHttpResponse response)
            throws Exception {
        logger.debug("Executing outbound handler.");
    }
}

HttpChannelInitializer.java

@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("decoder", new HttpRequestDecoder());
    pipeline.addLast("aggregator", new HttpObjectAggregator(1048576);
    pipeline.addLast("compressor", new HttpContentCompressor(gzipLevel));
    pipeline.addLast("outboundHandler", outboundHandler);
    pipeline.addLast(eventExecutorGroup, "inboundHandler", inboundHandler);
}

最后,这是记录器的输出。

[DEBUG] (Slf4JLogger:71) - [id: 0xbddf00cf, /0:0:0:0:0:0:0:1:57402 => /0:0:0:0:0:0:0:1:8080] ACTIVE
[DEBUG] (HttpOutboundHandler:19) - Executing outbound handler.
[DEBUG] (Slf4JLogger:71) - [id: 0x942993c1, /0:0:0:0:0:0:0:1:57403 :> /0:0:0:0:0:0:0:1:8080] INACTIVE
4

1 回答 1

3

回答我自己的问题,以防其他人发现这一点。

事实证明,我需要将消息添加到下一个出站消息缓冲区(我相信这具有将其传递给链中的下一个处理程序的效果)。我还需要保留消息。更新后的代码现在看起来像......

public class HttpOutboundHandler extends ChannelOutboundMessageHandlerAdapter<DefaultFullHttpResponse> {
    private static final Logger logger = LoggerFactory.getLogger(HttpOutboundHandler.class);

    @Override
    public void flush(ChannelHandlerContext context, DefaultFullHttpResponse response)
            throws Exception {
        logger.debug("Executing outbound handler.");
        ChannelHandlerUtil.addToNextOutboundBuffer(context, response.retain());
    }
}
于 2013-05-10T16:26:24.640 回答