【Netty】SimpleChannelInboundHandler如何根据数据类型处理消息

类匹配机制
  1. SimpleChannelInboundHandler在构造时,会通过泛型获取要处理的消息类型
  2. 在经过解码器处理后,netty会根据具体的消息类型,将其传递给能够处理该类型的 handler
工作流程
解码器 ---->消息类型判断  ----> 对应类型的SimpleChannelInboundHandler
实现原理
泛型类型获取
public abstract class SimpleChannelInboundHandler<I> extends ChannelInboundHandlerAdapter {
    private final TypeParameterMatcher matcher;
    
    protected SimpleChannelInboundHandler() {
        // 通过泛型获取要处理的消息类型
        matcher = TypeParameterMatcher.find(this, SimpleChannelInboundHandler.class, "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 {
        // 检查消息类型是否匹配
        if (acceptInboundMessage(msg)) {
            @SuppressWarnings("unchecked")
            I imsg = (I) msg;
            // 如果匹配,调用 channelRead0 处理消息
            channelRead0(ctx, imsg);
        } else {
            // 如果不匹配,将消息传递给下一个处理器
            release = false;
            ctx.fireChannelRead(msg);
        }
    } finally {
        if (autoRelease && release) {
            ReferenceCountUtil.release(msg);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值