最近做项目发现Netty中的channel有channelRead 方法也有channelRead0 方法,
然后思考下这两个有什么区别呢?
我们来直接看源码
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。