作用及工作原理
Channel管道,类似工厂流水线,只不过流水线上的物品是 事件
所以ChannelPipeline 是一个用于处理 事件流 (Event Flows) 的流水线容器,
源代码里有这样解释一个事件流的处理方式:
Intercepting Filter
源码描述了 ChannelPipeLine Intercepting Filter 模式 来实现的。
关于 Intercepting Filter 官方描述:
http://www.oracle.com/technetwork/java/interceptingfilter-142169.html
结构图
结构图顺序图
Intercepting Filter顺序图职责链模式
按照官方描述里说的,ChannelPipeline 就是跟Tomcat Filter 原理差不多。
一样也是使用职责链模式去实现 ,在Java Web里就是Fitler,而在Netty ChannelPipeline里就是ChannelHandler, 每一个职责链上的 Handler/Filter 都会决定当前事件流是否继续传递到下一个 Handler/Filter。
具体可以参考 职责链模式 Responsibility Chain
ChannelPipeline 添加ChannelHandler 的顺序及实际执行的顺序:
For example, let us assume that we created the following pipeline:
ChannelPipeline p = ...;
p.addLast("1", new InboundHandlerA());
p.addLast("2", new InboundHandlerB());
p.addLast("3", new OutboundHandlerA());
p.addLast("4", new OutboundHandlerB());
p.addLast("5", new InboundOutboundHandlerX());
In the example above, the class whose name starts with Inbound means it is an inbound handler. The class whose name starts with Outbound means it is a outbound handler.
In the given example configuration, the handler evaluation order is 1, 2, 3, 4, 5 when an event goes inbound. When an event goes outbound, the order is 5, 4, 3, 2, 1. On top of this principle, ChannelPipeline skips the evaluation of certain handlers to shorten the stack depth:
- 3 and 4 don't implement ChannelInboundHandler, and therefore the actual evaluation order of an inbound event will be: 1, 2, and 5.
- 1 and 2 don't implement ChannelOutboundHandler, and therefore the actual evaluation order of a outbound event will be: 5, 4, and 3.
- If 5 implements both ChannelInboundHandler and ChannelOutboundHandler, the evaluation order of an inbound and a outbound event could be 125 and 543 respectively.
Snip20180122_51.png
简单概括就是:
事件流 入站(InBound) 时,ChannelHanndler是与ChannelPipeline添加Handler顺序保持一致的,而当
事件流 出站(OutBound) 时,ChannelHanndler是与ChannelPipeline添加Handler顺序相反的。
怎么创建ChannelPipeline
当一个Channel被创建时,ChannelPipeline 就会自动被创建,言下之意,Channel不可能独立存在或者说不可能离开了ChannelPipeline。
正因为这个情况,所以一般在为ServerBootstrap 指定handler 的时候使用ChannelInitializer类来初始化 ChannelPipeline 流水线里的各个 Handler。
ChannelInitializer 主要是重写了 父类ChannelHandlerAdapter的handlerAdded方法,在这里开始触发初始化操作。
网友评论