Netty源码分析-ChannelPipeline

Netty的ChannelPipeline和ChannelHandler机制类似于Servlet和Filter过滤器,在设计模式中是一种责任链模式。ChannelPipeline持有一系列ChannelHandler的链表,每个ChannelHandler可以对I/O事件进行拦截和处理。这样,I/O事件消息在ChannelPipeline中流动和传递时,可以根据配置的ChannelHandler实现不同的业务逻辑定制。

1.ChannelPipeline

ChannelPipeline负责ChannelHandler的管理和事件拦截调度。

1.1ChannelPipeline处理流程

下图展示了一个I/O事件消息通过ChannelPipeline进行处理的全过程。
1)读事件,底层的Socket.read()方法(such as {@link SocketChannel#read(ByteBuffer)})读取ByteBuf,然后出发channelRead事件,通过NioEventLoop会调用pipeline的fireChannelRead(Object msg)方法;然后消息依次被Inbound Handler链条拦截和调用。
2)写事件,当调用ChannelHandlerContext的write方法发送消息时,消息也会依次被Outbound Handler链条拦截和调用,并最终调用socket的write()方法将数据写出去。

ChannelPipeline事件处理流程图

由上也可以得知,Netty中的事件也分为InBound事件和OutBound事件,并有分别对应的Handler链条去处理。并且事件在Handler之间的传递是通过ChannelHandlerContext的fireIN_EVT()和OUT_EVT()方法触发和传递的。
对于InBound事件,这些触发方法有:

 *     <li>{@link ChannelHandlerContext#fireChannelRegistered()}</li>
 *     <li>{@link ChannelHandlerContext#fireChannelActive()}</li>
 *     <li>{@link ChannelHandlerContext#fireChannelRead(Object)}</li>
 *     <li>{@link ChannelHandlerContext#fireChannelReadComplete()}</li>
 *     <li>{@link ChannelHandlerContext#fireExceptionCaught(Throwable)}</li>
 *     <li>{@link ChannelHandlerContext#fireUserEventTriggered(Object)}</li>
 *     <li>{@link ChannelHandlerContext#fireChannelWritabilityChanged()}</li>
 *     <li>{@link ChannelHandlerContext#fireChannelInactive()}</li>
 *     <li>{@link ChannelHandlerContext#fireChannelUnregistered()}</li>

对于outBound事件,这些触发方法有:

 *     <li>{@link ChannelHandlerContext#bind(SocketAddress, ChannelPromise)}</li>
 *     <li>{@link ChannelHandlerContext#connect(SocketAddress, SocketAddress, ChannelPromise)}</li>
 *     <li>{@link ChannelHandlerContext#write(Object, ChannelPromise)}</li>
 *     <li>{@link ChannelHandlerContext#flush()}</li>
 *     <li>{@link ChannelHandlerContext#read()}</li>
 *     <li>{@link ChannelHandlerContext#disconnect(ChannelPromise)}</li>
 *     <li>{@link ChannelHandlerContext#close(ChannelPromise)}</li>
 *     <li>{@link ChannelHandlerContext#deregister(ChannelPromise)}</li>

1.2 ChannelPipeline源码分析

Netty中pipeline的默认实现类是DefaultChannelPipeline。看一下DefaultChannelPipeline的实现:
1)类型为AbstractChannelHandlerContext的两个对象head、tail,DefaultChannelPipeline是通过AbstractChannelHandlerContext将Handler进行串联成一个链条的。具体可见下边的添加Handler的过程分析。
2)该pipeline对应的channel。

public class DefaultChannelPipeline implements ChannelPipeline {
    final AbstractChannelHandlerContext head;
    final AbstractChannelHandlerContext tail;

    private final Channel channel;
    private final ChannelFuture succeededFuture;
    private final VoidChannelPromise voidPromise;
    private final boolean touch = ResourceLeakDetector.isEnabled();

    private Map<EventExecutorGroup, EventExecutor> childExecutors;
    private MessageSizeEstimator.Handle estimatorHandle;
    private boolean firstRegistration = true;
}

1.2.1 添加一个Handler过程分析

举例addLast方法是如何添加一个新的Handler的,这个方法值得我们非常仔细地去探讨一下。
addLast(EventExecutorGroup group, String name, ChannelHandler handler)
入参:1)EventExecutorGroup group,表示的是最终执行Handler的线程池;2)String name,代表该Handler的名字;3)ChannelHandler handler是需要添加的具体执行操作的Handler。
执行过程分析:
①. newContext会创建一个AbstractChannelHandlerContext,将EventExecutorGroup、ChannelHandler、name等封装到该对象中。
②.addLast0会将该AbstractChannelHandlerContext加入值ChannelPipeline得链条中去。代码可见下边,典型的链表追加操作
③.if (!registered)判断该Channel是否已经成功注册到EventLoop中:
1)如果没有的话,会创建一个CallbackTask(该task会执行ChannelHandler.handlerAdded),等到channel注册到EventLoop后回调执行该task
2)已经注册的话,后续会执行callHandlerAdded0,根据executor.inEventLoop()判断决定是在当前线程执行还是在新线程中执行。

    @Override
    public final ChannelPipeline addLast(EventExecutorGroup group, String name, ChannelHandler handler) {
        final AbstractChannelHandlerContext newCtx;
        synchronized (this) {
            checkMultiplicity(handler);
            newCtx = newContext(group, filterName(name, handler), handler);
            addLast0(newCtx);

            // If the registered is false it means that the channel was not registered on an eventloop yet.
            // In this case we add the context to the pipeline and add a task that will call
            // ChannelHandler.handlerAdded(...) once the channel is registered.
            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;
            }
        }
        callHandlerAdded0(newCtx);
        return this;
    }
    private void addLast0(AbstractChannelHandlerContext newCtx) {
        AbstractChannelHandlerContext prev = tail.prev;
        newCtx.prev = prev;
        newCtx.next = tail;
        prev.next = newCtx;
        tail.prev = newCtx;
    }

1.2.2 I/O事件执行过程分析

我们以一个I/O读事件作为一个代表对ChannelPipeline的执行过程进行分析,ChannelPipeline中对读事件的执行方法是fireChannelRead(Object msg)
通过代码分析,我们可以看到会直接执行到AbstractChannelHandlerContext类的方法invokeChannelRead(final AbstractChannelHandlerContext next, Object msg),入参为头指针head和对象msg。

    @Override
    public final ChannelPipeline fireChannelRead(Object msg) {
        AbstractChannelHandlerContext.invokeChannelRead(head, msg);
        return this;
    }

invokeChannelRead的方法中,还是会根据executor.inEventLoop()方法,根据用户的线程设置,最终调用到对应handler的channelRead方法。

    static void invokeChannelRead(final AbstractChannelHandlerContext next, Object msg) {
        final Object m = next.pipeline.touch(ObjectUtil.checkNotNull(msg, "msg"), next);
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeChannelRead(m);
        } else {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    next.invokeChannelRead(m);
                }
            });
        }
    }

    private void invokeChannelRead(Object msg) {
    //to detect if {@link ChannelHandler#handlerAdded(ChannelHandlerContext)} was called yet. If not return {@code false} and if called or could not detect return {@code true}.
        if (invokeHandler()) {
            try {
                ((ChannelInboundHandler) handler()).channelRead(this, msg);
            } catch (Throwable t) {
                notifyHandlerException(t);
            }
        } else {
            fireChannelRead(msg);
        }
    }

2. ChannelHandler

先看一些类的继承图:

image.png

2.1 ChannelHandler中的方法

Netty定义了良好的类型层次结构来表示不同的处理程序类型,所有的类型的父类是ChannelHandler。ChannelHandler提供了在其生命周期内添加或从ChannelPipeline中删除的方法。
1). handlerAdded,ChannelHandler添加到实际上下文中准备处理事件
2). handlerRemoved,将ChannelHandler从实际上下文中删除,不再处理事件
3). exceptionCaught,处理抛出的异常
2、ChannelInboundHandler
ChannelInboundHandler提供了一些方法再接收数据或Channel状态改变时被调用。下面是ChannelInboundHandler的一些方法: 1). channelRegistered,ChannelHandlerContext的Channel被注册到EventLoop; 2). channelUnregistered,ChannelHandlerContext的Channel从EventLoop中注销 3). channelActive,ChannelHandlerContext的Channel已激活 4). channelInactive,ChannelHanderContxt的Channel结束生命周期 5). channelRead,从当前Channel的对端读取消息 6). channelReadComplete,消息读取完成后执行 7). userEventTriggered,一个用户事件被触发 8). channelWritabilityChanged,改变通道的可写状态,可以使用Channel.isWritable()检查 9). exceptionCaught,重写父类ChannelHandler的方法,处理异常.
举一个最常用的MessageToMessageDecoder作为例子,执行decode将msg对象进行转换后,如果想继续在Pipeline中继续传递下去,必须显示地去执行ctx.fireChannelRead方法,会通过AbstractChannelHandlerContext继续轮转到下一个ChannelHandler去执行。

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        CodecOutputList out = CodecOutputList.newInstance();
        try {
            if (acceptInboundMessage(msg)) {
                @SuppressWarnings("unchecked")
                I cast = (I) msg;
                try {
                    decode(ctx, cast, out);
                } finally {
                    ReferenceCountUtil.release(cast);
                }
            } else {
                out.add(msg);
            }
        } catch (Exception e) {
            throw new DecoderException(e);
        } finally {
            int size = out.size();
            for (int i = 0; i < size; i ++) {
                ctx.fireChannelRead(out.getUnsafe(i));
            }
            out.recycle();
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容