Netty4(十三):SimpleChannelInBoundH
2018-03-24 本文已影响87人
聪明的奇瑞
- SimpleChannelInboundHandler 继承于 ChannelHandlerAdapter,通过加入泛型可以使我们拦截特定类型的对象来进行处理
- 下面是 SimpleChannelInboundHandler 的源码:
public abstract class SimpleChannelInboundHandler<I> extends ChannelHandlerAdapter {
//类型匹配器
private final TypeParameterMatcher matcher;
// 是否自动释放 ByteBuf,refCount减一
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) {
matcher = TypeParameterMatcher.get(inboundMessageType);
this.autoRelease = autoRelease;
}
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 {
if (acceptInboundMessage(msg)) {
//判断消息是否为指定的处理的类型
@SuppressWarnings("unchecked")
I imsg = (I) msg;
channelRead0(ctx, imsg);
} else {
//如果不是,则不处理,传入 ChannelPipeline 给下一个 Handler 处理
release = false;
ctx.fireChannelRead(msg);
}
} finally {
if (autoRelease && release) {
ReferenceCountUtil.release(msg);
}
}
}
// 用于让子类重写该方法来处理实际处理
protected abstract void channelRead0(ChannelHandlerContext ctx, I msg) throws Exception;
}