netty笔记-ChannelHandler

1.生命周期

2.ChannelInboundHandler事件

3.ByteBuf的释放

3.1显式释放

3.2 SimpleChannelInboundHandler自动释放

重写channelRead0方法

public class SimpleDiscardHandler
extends SimpleChannelInboundHandler {
@Override
public void channelRead0(ChannelHandlerContext ctx,
Object msg) {
// No need to do anything special
 }
}
 
 

参考:
Netty4(十三):SimpleChannelInBoundHandler 源码分析

4.ChannelOutboundHandler事件

出站操作和数据将由 ChannelOutboundHandler 处理。它的方法将被 Channel、ChannelPipeline 以及 ChannelHandlerContext 调用。
ChannelOutboundHandler 的一个强大的功能是可以按需推迟操作或者事件,这使得可
以通过一些复杂的方法来处理请求。例如, 如果到远程节点的写入被暂停了, 那么你可以推迟冲
刷操作并在稍后继续。
表6-4显示了所有由ChannelOutboundHandler本身所定义的方法(忽略了那些从ChannelHandler 继承的方法)

5.ChannelHandler适配器

6.ChannelDuplexHandler

同时实现了ChannelInboundHandler和ChannelOutboundHandler

public class ChannelDuplexHandler extends ChannelInboundHandlerAdapter implements ChannelOutboundHandler {
}

7.CombinedChannelDuplexHandler

CombinedChannelDuplexHandler继承自ChannelDuplexHandler,其需要传入ChannelInboundHandler和ChannelOutboundHandler,本质上其是一个代理对象

public class CombinedChannelDuplexHandler
        extends ChannelDuplexHandler {

    private static final InternalLogger logger = InternalLoggerFactory.getInstance(CombinedChannelDuplexHandler.class);

    private DelegatingChannelHandlerContext inboundCtx;
    private DelegatingChannelHandlerContext outboundCtx;
    private volatile boolean handlerAdded;

    private I inboundHandler;
    private O outboundHandler;

    /**
     * Creates a new uninitialized instance. A class that extends this handler must invoke
     * {@link #init(ChannelInboundHandler, ChannelOutboundHandler)} before adding this handler into a
     * {@link ChannelPipeline}.
     */
    protected CombinedChannelDuplexHandler() {
        ensureNotSharable();
    }

    /**
     * Creates a new instance that combines the specified two handlers into one.
     */
    public CombinedChannelDuplexHandler(I inboundHandler, O outboundHandler) {
        ensureNotSharable();
        init(inboundHandler, outboundHandler);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        assert ctx == inboundCtx.ctx;
        if (!inboundCtx.removed) {
            inboundHandler.channelActive(inboundCtx);
        } else {
            inboundCtx.fireChannelActive();
        }
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        assert ctx == outboundCtx.ctx;
        if (!outboundCtx.removed) {
            outboundHandler.write(outboundCtx, msg, promise);
        } else {
            outboundCtx.write(msg, promise);
        }
    }
}

你可能感兴趣的:(netty笔记-ChannelHandler)