Netty源码分析系列

Netty源码分析系列--9. ChannelHandlerCo

2018-11-05  本文已影响15人  ted005

添加ChannelHandler到ChannelPipeline中

在上节中介绍了ChannelPipeline,其中常用的方法是addLast(handler)将各类ChannelHandler实例添加到ChannelChannelPipeline中。下面我们来看addLast(handler)方法的实现:

// 接受的第一个参数是事件执行组,当Handler的处理比较耗时时,可以指定其回调方法在事件执行组EventExecutorGroup中执行
@Override
public final ChannelPipeline addLast(EventExecutorGroup group, String name, ChannelHandler handler) {
        final AbstractChannelHandlerContext newCtx;
        synchronized (this) {
            checkMultiplicity(handler);

            // 1. 创建ChannelHandlerContext
            newCtx = newContext(group, filterName(name, handler), handler);

            // 2. 将ChannelHandlerContext加入到ChannelPipeline中
            addLast0(newCtx);

            if (!registered) {
                newCtx.setAddPending();
                callHandlerCallbackLater(newCtx, true);
                return this;
            }

            EventExecutor executor = newCtx.executor();
            if (!executor.inEventLoop()) {
                newCtx.setAddPending();
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        callHandlerAdded0(newCtx);
                    }
                });
                return this;
            }
        }
    
        // 3. 调用ChannelHandler的handlerAdded方法
        callHandlerAdded0(newCtx);
        return this;
 }

ChannelInitializer

ChannelInitializer是一类特殊的ChannelHandlerChannel注册到EventLoop时,可以初始化Channel

ServerBootStrap绑定端口号的过程中,在initAndRegister方法中:一个ChannelInitializer被加入到ChannelPipeline中。

void init(Channel channel) throws Exception {

    //以上省略......
    ChannelPipeline p = channel.pipeline();

    final EventLoopGroup currentChildGroup = childGroup;
    final ChannelHandler currentChildHandler = childHandler;
     //省略部分代码......

    p.addLast(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(final Channel ch) throws Exception {
            final ChannelPipeline pipeline = ch.pipeline();
            ChannelHandler handler = config.handler();
            if (handler != null) {
                pipeline.addLast(handler);
            }

            ch.eventLoop().execute(new Runnable() {
                @Override
                public void run() {
                    pipeline.addLast(new ServerBootstrapAcceptor(
                            ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
                }
            });
        }
    });
}

更加本文第一部分描述,当一个ChannelHandler被加入到ChannelPipeline里后,会调用它的handlerAdded回调方法。因此我们来看一下ChannelInitializer的回调方法。

public abstract class ChannelInitializer<C extends Channel> extends ChannelInboundHandlerAdapter {
    
    protected abstract void initChannel(C ch) throws Exception;

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        if (ctx.channel().isRegistered()) {
            initChannel(ctx);
        }
    }

    @SuppressWarnings("unchecked")
    private boolean initChannel(ChannelHandlerContext ctx) throws Exception {
        if (initMap.putIfAbsent(ctx, Boolean.TRUE) == null) {
            try {
                // 1. 初始化Channel
                initChannel((C) ctx.channel());
            } catch (Throwable cause) {
                exceptionCaught(ctx, cause);
            } finally {
                // 2. 从ChannelPipeline中移除
                remove(ctx);
            }
            return true;
        }
        return false;
    }

    private void remove(ChannelHandlerContext ctx) {
        try {
            ChannelPipeline pipeline = ctx.pipeline();
            if (pipeline.context(this) != null) {
                pipeline.remove(this);
            }
        } finally {
            initMap.remove(ctx);
        }
    }
}

从以上代码可以看到,handlerAdded方法首先调用initChannel 方法用来添加各种ChannelHandler实例,然后在finally中调用remove,把当前ChannelInitializerChannelPipeline中移除,因此ChannelInitializer可以理解为是一次性的。

上一篇 下一篇

猜你喜欢

热点阅读