16. ChannelPipeline of Netty source code


highlight: arduino-light

Service orchestration layer: ChannelPipeline coordinates ChannelHandlerHandler

EventLoop can be said to be the scheduling center of Netty, which is responsible for monitoring various event types: I/O events, signal events, timing events, etc. However, the actual business processing logic is completed by the ChannelHandler defined in the ChannelPipeline, and the ChannelPipeline and ChannelHandler applications The most frequently encountered components during development.

The core components of the Netty service orchestration layer, ChannelPipeline and ChannelHandler, provide users with full control over I/O events.

Before learning, think about a few questions.

  • What is the relationship between ChannelPipeline and ChannelHandler? How do they work together?
  • What are the types of ChannelHandler? What's the difference?
  • How are I/O events propagated in Netty?

ChannelPipeline overview

Pipeline literally means pipeline, pipeline. Its role in Netty is similar to the assembly line of a factory.

The original network byte stream passes through the Pipeline, is processed and packaged step by step, and finally the processed product is obtained.

After the preliminary study of the core components of the previous courses, we have already had a preliminary impression of ChannelPipeline: it is the core processing chain of Netty, which is used to realize the dynamic arrangement and orderly dissemination of network events.

Today we will discuss the implementation principle of ChannelPipeline from the following aspects:

  • ChannelPipeline internal structure;
  • ChannelHandler interface design;
  • ChannelPipeline event propagation mechanism;
  • ChannelPipeline exception propagation mechanism.

ChannelPipeline internal structure

ChannelPipeline can be regarded as the container carrier of ChannelHandler. It is composed of a group of ChannelHandler instances, and different ChannelHandlers are linked together through a doubly linked list internally, as shown in the figure below.

When an I/O read/write event is triggered, ChannelPipeline will call the ChannelHandler list in turn to intercept and process the Channel data.

image.png

Each ChannelHandler corresponds to a ChannelHandlerContext.

So in fact ChannelPipeline maintains its relationship with ChannelHandlerContext.

Then you may have a question, why is there an extra layer of ChannelHandlerContext encapsulation?

In fact, this is a relatively common programming idea. ChannelHandlerContext is used to save ChannelHandler.

ChannelHandlerContext contains all events of the ChannelHandler life cycle, such as connect, bind, read, flush, write, close, etc.

Just imagine, if there is no encapsulation of ChannelHandlerContext, then we are passing between ChannelHandlers. The general logic of pre-post and post-position must be implemented in each ChannelHandler.

Although this can solve the problem, the coupling of the code structure will be very inelegant.

According to the flow direction of network data, ChannelPipeline is divided into inbound ChannelInboundHandler and outbound ChannelOutboundHandler.

After the server receives the data from the client, it needs to go through the inbound processing of the Decoder, and then notify the client through the outbound Encoder.

image.png

ChannelPipeline is a construction of a doubly linked list .

ChannelPipeline 的双向链表分别维护了HeadContext 和 TailContext 的头尾节点。

我们自定义的ChannelHandler会插入到 Head 和 Tail 之间,这两个节点在 Netty 中已经默认实现了,它们在

ChannelPipeline 中起到了至关重要的作用。

首先我们看下 HeadContext 和 TailContext 的继承关系,如下图所示。

image.png

HeadContext:in\&out

对于1个请求先由HeadContext处理入栈,经过一系列的入栈处理器然后传递到TailContext,由TailContext往下传递经过一系列的出栈处理器,最后再经过HeadContext返回。 ```md

<---6 <---5 <---4 HeadContext InBoundHandlerOne TailContext OutBoundHandlerOne 1---> 2---> 3--->

顺序是:12346 其中5是入栈已经在2处理过 所以不需要处理。 ```

Inbound第一站

Outbound最后一站

HeadContext 既是 Inbound 处理器,也是 Outbound 处理器。 它分别实现了 ChannelInboundHandler 和 ChannelOutboundHandler。

网络数据写入操作的入口就是由 HeadContext 节点完成的。HeadContext 作为 Pipeline 的头结点负责读取数据并开始传递 InBound 事件,当数据处理完成后,数据会反方向经过 Outbound 处理器,最终传递到 HeadContext,所以 HeadContext 既是数据读取Inbound事件的第一站又是处理 Outbound 事件的最后一站。

此外 HeadContext 在传递事件之前,还会执行一些前置操作。

TailContext

Outbound第一站

TailContext 只实现了 ChannelInboundHandler 接口。它会在 ChannelInboundHandler 调用链路的最后一步执行,主要用于终止 Inbound 事件传播,例如释放 Message 数据资源等。

TailContext 节点作为 OutBound 事件传播的第一站,仅仅是将 OutBound 事件传递给下一个节点。

从整个 ChannelPipeline 调用链路来看,如果由 Channel 直接触发事件传播,那么调用链路将贯穿整个 ChannelPipeline。

然而也可以在其中某一个 ChannelHandlerContext 触发同样的方法,这样只会从当前的 ChannelHandler 开始执行事件传播,该过程不会从头贯穿到尾,在一定场景下,可以提高程序性能。

ChannelHandler 接口设计

在学习 ChannelPipeline 事件传播机制之前,我们需要了解 I/O 事件的生命周期。

整个 ChannelHandler 是围绕 I/O 事件的生命周期所设计的,例如建立连接、读数据、写数据、连接销毁等。

ChannelHandler 有两个重要的子接口ChannelInboundHandlerChannelOutboundHandler,分别拦截

站和出站的各种 I/O 事件

1. ChannelInboundHandler 的事件回调方法与触发时机。

| 事件回调方法 | 触发时机 | | ------------------------- | --------------------------------- | | channelRegistered | Channel 被注册到 EventLoop | | channelUnregistered | Channel 从 EventLoop 中取消注册 | | channelActive | Channel 处于就绪状态,可以被读写 | | channelInactive | Channel 处于非就绪状态Channel 可以从远端读取到数据 | | channelRead | Channel 可以从远端读取到数据 | | channelReadComplete | Channel 读取数据完成 | | userEventTriggered | 用户事件触发时 | | channelWritabilityChanged | Channel 的写状态发生变化 | | handlerAdded | 当该处理器被添加到pipeline时 |

2. ChannelOutboundHandler 的事件回调方法与触发时机。

ChannelOutboundHandler 的事件回调方法非常清晰,直接通过 ChannelOutboundHandler 的接口列表可以看到每种操作所对应的回调方法,如下图所示。

这里每个回调方法都是在相应操作执行之前触发,在此就不多做赘述了。

此外 ChannelOutboundHandler 中绝大部分接口都包含ChannelPromise 参数,以便于在操作完成时能够及时获得通知。

image.png

事件

事件枚举

public static final int OP_READ = 1 << 0;//1
public static final int OP_WRITE = 1 << 2;//4
public static final int OP_CONNECT = 1 << 3;//8
public static final int OP_ACCEPT = 1 << 4;//16

事件传播机制

在上文中我们介绍了 ChannelPipeline 可分为入站 ChannelInboundHandler 和出站 ChannelOutboundHandler 两种处理器,与此对应传输的事件类型可以分为Inbound 事件Outbound 事件

我们通过一个代码示例,一起体验下 ChannelPipeline 的事件传播机制。 ```java package io.netty.example.pipeline;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * Echoes back any received data from a client.
 */
public final class EchoServer {

    public static void main(String[] args) throws Exception {

        EventLoopGroup workerGroup = new NioEventLoopGroup();
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();

            b.group(bossGroup, workerGroup)
                    //通过反射创建反射工厂类根据无参构造函数 反射生成实例
                    //将NioServerSocketChannel绑定到了bossGroup
                    //NioServerSocketChannel接收到请求会创建SocketChannel放入workerGroup
                    .channel(NioServerSocketChannel.class)

                    //指的是SocketChannel
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    //指的是SocketChannel
                    .childOption(NioChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                    //默認不使用堆外内存
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    //false 不使用堆外内存
                    .childOption(ChannelOption.ALLOCATOR, 
                                    new UnpooledByteBufAllocator(false))
                    //   .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            //正常情况
                            p.addLast("SampleInBoundHandlerA", new SampleInBoundHandler("SampleInBoundHandlerA", false));
                            p.addLast("SampleInBoundHandlerB", new SampleInBoundHandler("SampleInBoundHandlerB", false));
                            p.addLast("SampleInBoundHandlerC", new SampleInBoundHandler("SampleInBoundHandlerC", true));




                            p.addLast("SampleOutBoundHandlerA", new SampleOutBoundHandler("SampleOutBoundHandlerA"));
                            p.addLast("SampleOutBoundHandlerB", new SampleOutBoundHandler("SampleOutBoundHandlerB"));
                            p.addLast("SampleOutBoundHandlerC", new SampleOutBoundHandler("SampleOutBoundHandlerC"));
                        }
                    });

            ChannelFuture f = b.bind(8090).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
package io.netty.example.pipeline;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;


public final class EchoClient {

    public static void main(String[] args) throws Exception {
        // Configure the client.
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioSocketChannel.class)
             .option(ChannelOption.TCP_NODELAY, true)
             .handler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ChannelPipeline p = ch.pipeline();
                     p.addLast(new EchoClientHandler());
                 }
             });

            // Start the client.
            ChannelFuture f = b.connect("127.0.0.1", 8090).sync();

            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } finally {
            // Shut down the event loop to terminate all threads.
            group.shutdownGracefully();
        }
    }
}
package io.netty.example.pipeline;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.TimeUnit;

/**
 * Handler implementation for the echo client.  It initiates the ping-pong
 * traffic between the echo client and server by sending the first message to
 * the server.
 */
public class EchoClientHandler extends ChannelInboundHandlerAdapter {

    private final ByteBuf firstMessage;

    /**
     * Creates a client-side handler.
     */
    public EchoClientHandler() {
        firstMessage = Unpooled.wrappedBuffer("I am echo message".getBytes());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("客户端发送消息" + firstMessage.toString());
        ctx.writeAndFlush(firstMessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
       // ctx.write(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
       // cause.printStackTrace();
        ctx.close();
    }
}
package io.netty.example.pipeline;

import io.netty.channel.*;

public class SampleInBoundHandler extends ChannelInboundHandlerAdapter {
  private final String name;
  private final boolean flush;

  public SampleInBoundHandler(String name, boolean flush) {
    this.name = name;
    this.flush = flush;
  }

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
      //打印消息
      System.out.println("InBoundHandler: " + name);
    //只有是true的时候才会写消息
    //否则只会读消息
    if (flush) {
      ctx.channel().writeAndFlush(msg);
    } else {
      super.channelRead(ctx, msg);
    }
  }
}
package io.netty.example.pipeline;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

public class SampleOutBoundHandler extends ChannelOutboundHandlerAdapter {
  private final String name;
  public SampleOutBoundHandler(String name) {
    this.name = name;
  }

  @Override
  public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    System.out.println("OutBoundHandler: " + name);
    super.write(ctx, msg, promise);
  }
}

```

通过 Pipeline 的 addLast 方法分别添加了三个 InboundHandler 和 OutboundHandler,添加顺序都是 A -> B -> C,下图可以表示初始化后 ChannelPipeline 的内部结构。

image.png

*当客户端向服务端发送请求时,会触发 SampleInBoundHandler 调用链的 channelRead 事件。经过 SampleInBoundHandler 调用链处理完成后,在 SampleInBoundHandlerC 中会调用 writeAndFlush 方法向客户端写回数据,此时会触发 SampleOutBoundHandler 调用链的 write 事件。** 最后我们看下代码示例的控制台输出:

image (3).png

方向:IN先进先出OUT:先进后出

由此可见,Inbound 事件和 Outbound 事件的传播方向是不一样的。Inbound 事件的传播方向为 Head -> Tail,而 Outbound 事件传播方向是 Tail -> Head,两者恰恰相反。 在 Netty 应用编程中一定要理清楚事件传播的顺序。推荐你在系统设计时模拟客户端和服务端的场景画出 ChannelPipeline 的内部结构图,以避免搞混调用关系。

异常传播机制

ChannelPipeline 事件传播的实现采用了经典的责任链模式,调用链路环环相扣。那么如果有一个节点处理逻辑异常会出现什么现象呢?我们通过修改 SampleInBoundHandler 的实现来模拟业务逻辑异常: ```java package io.netty.example.pipeline;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * Echoes back any received data from a client.
 */
public final class EchoServer {

    public static void main(String[] args) throws Exception {

        EventLoopGroup workerGroup = new NioEventLoopGroup();
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();

            b.group(bossGroup, workerGroup)
                    //通过反射创建反射工厂类根据无参构造函数 反射生成实例
                    //将NioServerSocketChannel绑定到了bossGroup
                    //NioServerSocketChannel接收到请求会创建SocketChannel放入workerGroup
                    .channel(NioServerSocketChannel.class)

                    //指的是SocketChannel
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    //指的是SocketChannel
                    .childOption(NioChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                    //默認不使用堆外内存
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    //false 不使用堆外内存
                    .childOption(ChannelOption.ALLOCATOR, new UnpooledByteBufAllocator(false))
                    //   .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            //正常情况
                          /*
                            p.addLast("SampleInBoundHandlerA", new SampleInBoundHandler("SampleInBoundHandlerA", false));
                            p.addLast("SampleInBoundHandlerB", new SampleInBoundHandler("SampleInBoundHandlerB", false));
                            p.addLast("SampleInBoundHandlerC", new SampleInBoundHandler("SampleInBoundHandlerC", true));
                            */

                            p.addLast("SampleInBoundHandlerA", new SampleExceptionInBoundHandler("SampleInBoundHandlerA", false));
                            p.addLast("SampleInBoundHandlerB", new SampleExceptionInBoundHandler("SampleInBoundHandlerB", false));
                            p.addLast("SampleInBoundHandlerC", new SampleExceptionInBoundHandler("SampleInBoundHandlerC", true));

                            p.addLast("SampleOutBoundHandlerA", new SampleOutBoundHandler("SampleOutBoundHandlerA"));
                            p.addLast("SampleOutBoundHandlerB", new SampleOutBoundHandler("SampleOutBoundHandlerB"));
                            p.addLast("SampleOutBoundHandlerC", new SampleOutBoundHandler("SampleOutBoundHandlerC"));
                        }
                    });

            ChannelFuture f = b.bind(8090).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
package io.netty.example.pipeline;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class SampleExceptionInBoundHandler extends ChannelInboundHandlerAdapter {
    private final String name;
    private final boolean flush;
    public SampleExceptionInBoundHandler(String name, boolean flush) {
        this.name = name;
        this.flush = flush;
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println("InBoundHandler: " + name);
        if (flush) {
            ctx.channel().writeAndFlush(msg);
        } else {
            throw new RuntimeException("InBoundHandler: " + name);
        }
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("InBoundHandlerException: " + name);
        ctx.fireExceptionCaught(cause);
    }
}

``` 在SampleExceptionInBoundHandler的 channelRead 事件处理中,第一个 A 节点就会抛出 RuntimeException。同时我们重写了 ChannelInboundHandlerAdapter 中的 exceptionCaught 方法,只是在开头加上了控制台输出,方便观察异常传播的行为。下面看一下代码运行的控制台输出结果:

image (4).png

由输出结果可以看出 ctx.fireExceptionCaugh 会将异常按顺序从 Head 节点传播到 Tail 节点

如果用户没有对异常进行拦截处理,最后将由 Tail 节点统一处理,在 TailContext 源码中可以找到具体实现:

protected void onUnhandledInboundException(Throwable cause) {

    try {
    logger.warn("An exceptionCaught() event was fired, and it reached at the tail of the pipeline. " + "It usually means the last handler in the pipeline did not handle the exception.",cause);
    } finally {
        ReferenceCountUtil.release(cause);
    }
}

虽然 Netty 中 TailContext 提供了兜底的异常处理逻辑,但是在很多场景下,并不能满足我们的需求。假如你需要拦截指定的异常类型,并做出相应的异常处理,应该如何实现呢?我们接着往下看。

异常处理的最佳实践

在 Netty 应用开发的过程中,良好的异常处理机制会让排查问题的过程事半功倍。所以推荐用户对异常进行统一拦截,然后根据实际业务场景实现更加完善的异常处理机制。

通过异常传播机制的学习,我们应该可以想到最好的方法是在 ChannelPipeline 自定义处理器的末端添加统一的异常处理器,此时 ChannelPipeline 的内部结构如下图所示。

image.png

用户自定义的异常处理器代码示例如下: ```java package io.netty.example.pipeline;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * Echoes back any received data from a client.
 */
public final class EchoServer {

    public static void main(String[] args) throws Exception {

        EventLoopGroup workerGroup = new NioEventLoopGroup();
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();

            b.group(bossGroup, workerGroup)
                    //通过反射创建反射工厂类根据无参构造函数 反射生成实例
                    //将NioServerSocketChannel绑定到了bossGroup
                    //NioServerSocketChannel接收到请求会创建SocketChannel放入workerGroup
                    .channel(NioServerSocketChannel.class)

                    //指的是SocketChannel
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    //指的是SocketChannel
                    .childOption(NioChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                    //默認不使用堆外内存
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    //false 不使用堆外内存
                    .childOption(ChannelOption.ALLOCATOR, new UnpooledByteBufAllocator(false))
                    //   .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            //正常情况
                          /*
                            p.addLast("SampleInBoundHandlerA", new SampleInBoundHandler("SampleInBoundHandlerA", false));
                            p.addLast("SampleInBoundHandlerB", new SampleInBoundHandler("SampleInBoundHandlerB", false));
                            p.addLast("SampleInBoundHandlerC", new SampleInBoundHandler("SampleInBoundHandlerC", true));
                            */

                            p.addLast("SampleInBoundHandlerA", new SampleExceptionInBoundHandler("SampleInBoundHandlerA", false));
                            p.addLast("SampleInBoundHandlerB", new SampleExceptionInBoundHandler("SampleInBoundHandlerB", false));
                            p.addLast("SampleInBoundHandlerC", new SampleExceptionInBoundHandler("SampleInBoundHandlerC", true));

                            //添加异常处理器
                            p.addLast(new ExceptionHandler());

                            p.addLast("SampleOutBoundHandlerA", new SampleOutBoundHandler("SampleOutBoundHandlerA"));
                            p.addLast("SampleOutBoundHandlerB", new SampleOutBoundHandler("SampleOutBoundHandlerB"));
                            p.addLast("SampleOutBoundHandlerC", new SampleOutBoundHandler("SampleOutBoundHandlerC"));
                        }
                    });

            ChannelFuture f = b.bind(8090).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
//进站出站异常处理器
public class ExceptionHandler extends ChannelDuplexHandler {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (cause instanceof RuntimeException) {
            System.out.println("Handle Business Exception Success.");
        }
    }
}

``` 加入统一的异常处理器后,可以看到异常已经被优雅地拦截并处理掉了。这也是 Netty 推荐的最佳异常处理实践。

image (5).png

总结

本节课我们深入分析了 Pipeline 的设计原理与事件传播机制。

那么前面的几个问题你是否已经都找到答案,来做个简单的总结:

  • ChannelPipeline 是双向链表结构,包含 ChannelInboundHandler 和 ChannelOutboundHandler 两种处理器。
  • ChannelHandlerContext 是对 ChannelHandler 的封装,每个 ChannelHandler 都对应一个 ChannelHandlerContext,实际上 ChannelPipeline 维护的是与 ChannelHandlerContext 的关系。
  • Inbound 事件和 Outbound 事件的传播方向相反,Inbound 事件的传播方向为 Head -> Tail,而 Outbound 事件传播方向是 Tail -> Head。
  • 异常事件的处理顺序与 ChannelHandler 的添加顺序相同,会依次向后传播,与 Inbound 事件和 Outbound 事件无关。

Guess you like

Origin blog.csdn.net/qq_30635523/article/details/131977908