最近做项目发现Netty中的channel有channelRead 方法也有channelRead0 方法,
然后思考下这两个有什么区别呢?
我们来直接看源码
@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
Netty的channelRead方法是一个公共方法,用于外部调用,它首先进行消息类型检查,判断是否需要传递给下一个handler。而channelRead0是受保护的方法,仅在内部使用,被channelRead调用,执行实际的消息读取操作。这一设计允许自定义处理流程并确保消息传递的控制。

1万+

被折叠的 条评论
为什么被折叠?



