概述
fireChannelRead
表示传递消息至下一个处理器,因为pipline的原因,我们可能有一个链式的处理队列,这个队列有头和尾之分,那么消息通常从头处理器进入。
假设现有队列A、B、C,一条消息消息首先进入A,如果A不显示调用fireChannelRead将消息传递至B的话,那么B和C永远收不到消息。
我们来看个例子:
public class AHandler extends ChannelInboundHandlerAdapter {
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ctx.fireChannelRead(msg);
上面的例子表示A处理器把msg透传给了B,当然了,A不一定直接透传,也可以传递处理过的消息。我们来看个例子:
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
byte[] bytes = new byte[buf.readableBytes()];
// 读取输入的消息至byte数组
buf.readBytes(bytes);
int length = bytes.length + 1;
ByteBuf newBuf = ctx.alloc().buffer(length);
newBuf.writeBytes(bytes);
// 多写入一个boolean类型的数据
newBuf.writeBoolean(false);
ReferenceCountUtil.release(msg);
ctx.fireChannelRead(newBuf);
}
这个例子是在原有的消息之上,封装了一个boolean类型的数据,然后再传递至下一个处理器。
注意:
ctx.fireChannelRead(msg); 不能将已释放的msg传入
建议:
继承SimpleChannelInboundHandler,因为SimpleChannelInboundHandler已经帮我们 把与业务无关的逻辑在ChannelRead方法实现了,我们只需要实现它的channelRead0方法来完成我们的逻辑就够了:
注意初始化SimpleChannelInboundHandler时参数autoRelease
是否释放 msg 默认true channelRead0
最后自动释放
参考
【Netty】ChannelHandler和ChannelPipeline