1. ChannelInboundHandlerAdapter与SimpleChannelInboundHandler的简介
在netty4.0.X版本中,ChannelInboundHandlerAdapter是普通类,而SimpleChannelInboundHandler<T>是抽象类。
SimpleChannelInboundHandler<T>有一个重要特性,就是消息被读取后,会自动释放资源,常见的IM聊天软件的机制就类似这种。
绝大部分场景都可以用ChannelInboundHandlerAdapter来处理。
2. SimpleChannelInboundHandler介绍
SimpleChannelInboundHandler类是继承了ChannelInboundHandlerAdapter类,新增了抽象channelRead0方法 和 重写了channelRead()方法。
public abstract class SimpleChannelInboundHandler<I> extends ChannelInboundHandlerAdapter{ ... }
protected abstract void channelRead0(ChannelHandlerContext ctx, I msg) throws Exception;
把处理逻辑不变的内容写好在 channelRead(ctx,msg) 中,并且在里面调用 channelRead0 ,这样变化的内容通过抽象方法实现传递到子类中去了(在Netty5中channelRead0已被重命名为messageReceived)。
@Override// 继承了 ChannelInboundHandlerAdapter#channelRead
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
boolean release = true;
try {
if (acceptInboundMessage(msg)) {
@SuppressWarnings("unchecked")
I imsg = (I) msg;
channelRead0(ctx, imsg);// 模板方法,抽出可变的部分,具体实现在子类中
} else {
release = false;
ctx.fireChannelRead(msg);
}
} finally {
if (autoRelease && release) {
ReferenceCountUtil.release(msg);// 释放资源(保存消息的ByteBuf)
}
}
}
我们知道,ChannelInboundHandlerAdapter 不会像 SimpleChannelInboundHandler 一样在 channelRead() 里面释放资源,而是在收到消息处理完成的事件时,当 writeAndFlush() 方法被调用时才会释放资源。
public void channelReadComplete(ChannelHandlerContext ctx)
throws Exception {
//将未决消息冲刷到远程节点,并且关闭该 Channel
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
.addListener(ChannelFutureListener.CLOSE);
}
public ChannelFuture writeAndFlush(Object msg) {
return writeAndFlush(msg, newPromise());// 跳转到另外一个重载的方法中
}
public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) {
if (msg == null) {// msg不能为空
throw new NullPointerException("msg");
}
if (isNotValidPromise(promise, true)) {
ReferenceCountUtil.release(msg);// 释放资源(保存消息的ByteBuf)
// cancelled
return promise;
}
write(msg, true, promise);// 异步写操作
return promise;
}
上面ChannelInboundHandlerAdapter 的源码中,最后资源是通过 ReferenceCountUtil 来释放的。也就是说,当我们需要释放ByteBuf相关内存的时候,也可以使用 ReferenceCountUtil#release()。
ReferenceCountUtil 底层实现是 ReferenceCounted ,当新的对象初始化的时候计数为1,retain() 方法被调用时引用计数加1,release()方法被调用时引用计数减1,当计数减少到0的时候会被显示清除,再次访问被清除的对象会出现访问冲突(这里想起了JVM判断对象是否存活的引用计数算法)。
ReferenceCountUtil#release:
public static boolean release(Object msg) {
if (msg instanceof ReferenceCounted) {
return ((ReferenceCounted) msg).release();// Decreases the reference count by 1
}
return false;
}
3. SimpleChannelInboundHandler 开发时要注意
在解码时,用参数ByteBuf做累加缓冲区,如下:
public class FTPMessageDecoder extends ByteToMessageDecoder {
// 解码方法,参数byteBuf就是累加缓冲区,out可以理解为一个列表,存放解码后的对象
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
int length = byteBuf.readableBytes();
if (length <= 0) return;
byte[] data = new byte[length];
byteBuf.readBytes(data);
list.add(Packet.create(data));
}
}
用继承SimpleChannelInboundHandler 时指定了参数类型<Packet>
public class FTPCommandFilterHandler extends SimpleChannelInboundHandler<Packet>{
如SimpleChannelInboundHandler源码所示,在调用 channelRead中的acceptInboundMessage方法判断msg是不是SimpleChannelInboundHandler中指定的类型:
@Override// 继承了 ChannelInboundHandlerAdapter#channelRead
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
boolean release = true;
try {
if (acceptInboundMessage(msg)) {
@SuppressWarnings("unchecked")
I imsg = (I) msg;
channelRead0(ctx, imsg);// 模板方法,抽出可变的部分,具体实现在子类中
} else {
release = false;
ctx.fireChannelRead(msg);
}
} finally {
if (autoRelease && release) {
ReferenceCountUtil.release(msg);// 释放资源(保存消息的ByteBuf)
}
}
}
所以只有在上一个channelHandler解码时,出参是Packet类型,与下一个channelHandler中SimpleChannelInboundHandler指定的类型一致,才能读到数据!!!