0
点赞
收藏
分享

微信扫一扫

Netty源码分析-SimpleChannelInboundHandler

芥子书屋 2022-02-08 阅读 63


package io.netty.channel;

import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.TypeParameterMatcher;


public abstract class SimpleChannelInboundHandler<I> extends ChannelInboundHandlerAdapter {

//类型参数匹配器(ReflectiveMatcher)实例
//匹配类定义中的类型I
private final TypeParameterMatcher matcher;
private final boolean autoRelease;


protected SimpleChannelInboundHandler() {
this(true);
}

protected SimpleChannelInboundHandler(boolean autoRelease) {
matcher = TypeParameterMatcher.find(this, SimpleChannelInboundHandler.class, "I");
this.autoRelease = autoRelease;
}

protected SimpleChannelInboundHandler(Class<? extends I> inboundMessageType) {
this(inboundMessageType, true);
}

protected SimpleChannelInboundHandler(Class<? extends I> inboundMessageType, boolean autoRelease) {
//类型参数匹配器(ReflectiveMatcher)实例
//匹配类定义中的类型I
matcher = TypeParameterMatcher.get(inboundMessageType);
this.autoRelease = autoRelease;
}

//I.isInstance(msg);
//判断msg是否是I类型或其子类
public boolean acceptInboundMessage(Object msg) throws Exception {
return matcher.match(msg);
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
boolean release = true;
try {
//如果msg是I类型或它的子类
if (acceptInboundMessage(msg)) {
@SuppressWarnings("unchecked")
//类型转换
I imsg = (I) msg;
//调用子类实现
channelRead0(ctx, imsg);
} else {
//交给下一个handle
release = false;
ctx.fireChannelRead(msg);
}
} finally {
//释放msg
if (autoRelease && release) {
ReferenceCountUtil.release(msg);
}
}
}

protected abstract void channelRead0(ChannelHandlerContext ctx, I msg) throws Exception;
}



举报

相关推荐

0 条评论