SimpleChannelInboundHandler和ChannelInboundHandlerAdapter的区别

1. 源码分析

  1. SimpleChannelInboundHandler
    @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);
            }
        }
    }
  1. ChannelInboundHandlerAdapter
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ctx.fireChannelRead(msg);
    }

从源码上上面,我们可以看出,当方法返回时,SimpleChannelInboundHandler会负责释放指向保存该消息的ByteBuf的内存引用。而ChannelInboundHandlerAdapter在其时间节点上不会释放消息,而是将消息传递给下一个ChannelHandler处理。

2. 从类定义看

  1. SimpleChannelInboundHandler
public abstract class SimpleChannelInboundHandler extends ChannelInboundHandlerAdapter {
  1. ChannelInboundHandlerAdapter
public class ChannelInboundHandlerAdapter extends ChannelHandlerAdapter implements ChannelInboundHandler

从类的定义中,我们可以看出

  • SimpleChannelInboundHandler是抽象类,而ChannelInboundHandlerAdapter是普通类,
  • SimpleChannelInboundHandler支持泛型的消息处理,而ChannelInboundHandlerAdapter不支持泛型

你可能感兴趣的:(SimpleChannelInboundHandler和ChannelInboundHandlerAdapter的区别)