Netty使用时有channelRead和channelRead0,它们什么区别?

公司项目中有看到同事在使用netty通讯时重写channelRead0这个方法进行接收数据,然后我在网上看教程有使用channelRead方法的,两个都是可以进行接收数据的,那区别是什么呢?

我们直接看一下源码 首先看channelRead:

@Override
    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);
            }
        }
    }

再来看下channelRead0:

protected abstract void channelRead0(ChannelHandlerContext ctx, I msg) throws Exception;
    可以很明显的看到,channelRead 是public 类型,可以被外部访问;而channelRead0是protected类型,只能被当前类及其子类访问 channelRead中调用了channelRead0,那么channelRead又额外多做了什么呢?
/**
     * Returns {@code true} if the given message should be handled. If {@code false} it will be passed to the next
     * {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
     */
    public boolean acceptInboundMessage(Object msg) throws Exception {
          
   
        return matcher.match(msg);
    }
    上面代码做了一个消息类型检查,判断是否传递到下一个handler

总结: channelRead 中调用了 channelRead0,其会先做消息类型检查,判断当前message 是否需要传递到下一个handler。

经验分享 程序员 微信小程序 职场和发展