netty ChannelInboundHandlerAdapter 使用注意事项

场景

下面是一段普通的channelHandler处理程序,主要是继承了ChannelInboundHandlerAdapter确是隐藏了巨大的错误

““
public class ServerBizHandler extends ChannelInboundHandlerAdapter {
private ChannelHandlerContext ctx;

@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    this.ctx = ctx;
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    super.channelRead(ctx, msg);
    log.debug("thread.name={}", Thread.currentThread().getName());

    ByteBuf in = (ByteBuf) msg;

    String readStr = in.toString(CharsetUtil.UTF_8);
    log.debug("Server received: {}", readStr);

    log.debug("release msg");
    ReferenceCountUtil.release(msg);
 }

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    ctx.flush();
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
    ctx.close();
}

}
““

先看下堆栈异常


io.netty.util.IllegalReferenceCountException: refCnt: 0
at io.netty.buffer.AbstractByteBuf.ensureAccessible(AbstractByteBuf.java:1173)
at io.netty.buffer.AbstractByteBuf.checkIndex(AbstractByteBuf.java:1119)
at io.netty.buffer.UnpooledUnsafeDirectByteBuf.internalNioBuffer(UnpooledUnsafeDirectByteBuf.java:385)
at io.netty.buffer.ByteBufUtil.decodeString(ByteBufUtil.java:568)
at io.netty.buffer.AbstractByteBuf.toString(AbstractByteBuf.java:979)
at io.netty.buffer.AbstractByteBuf.toString(AbstractByteBuf.java:974)
at com.spy.apollo.netty.demo.demo02_biz_logic.ServerBizHandler.channelRead(ServerBizHandler.java:50)

异常说是引用计数为0,也就是没有被引用,因此报错;常规的channelRead中消息读取完毕是要立即释放当前消息的引用计数即(减一操作)
ReferenceCountUtil.release(msg);

分析

通过调试代码发现根源就在super.channelRead(ctx, msg);这个函数

其实ChannelInboundHandlerAdapter 是提供了一种实现而已,子类如果要继承,需要覆盖父类中的方法,并且不需要调用super.xxxxMethod()
源码部分
这里写图片描述

这里写图片描述

再看看javadoc中ChannelInboundHandlerAdapter是怎么解释的
这里写图片描述

结论

  • 最简单的方式,使用ChannelInboundHandler
  • 使用ChannelInboundHandlerAdapter时 不需要调用super.xxxMethod()即可
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值