DefaultPipeline的创建
当我们创建Channel(NioServerSocketChannel、NioSocketChannel)的时候,会在父类的构造方法中,创建默认的Pipeline,代码如下所示:
为Channel创建默认的pipeline
protected AbstractChannel(Channel parent) {
this.parent = parent;
unsafe = newUnsafe();
pipeline = newChannelPipeline();
}
/**
* Returns a new {@link DefaultChannelPipeline} instance.
*/
protected DefaultChannelPipeline newChannelPipeline() {
return new DefaultChannelPipeline(this);
}
我们再来看一下pipeline的构造方法:
protected DefaultChannelPipeline(Channel channel) {
this.channel = ObjectUtil.checkNotNull(channel, "channel");
tail = new TailContext(this);
head = new HeadContext(this);
head.next = tail;
tail.prev = head;
}
可以看到,其默认提供了一个head、tail的AbstractChannelHandlerContext,这个类中包含一个用于处理特定事件handler以及向前和向后的引用,从而组成了pipeline的ctx双向链表。
Netty将ChannelHandler类型分为了两类:ChannelOutboundHandler, ChannelInboundHandler,分别用于处理入站事件和出站事件,下图分别为EventLoop处理OP_READ、OP_WRITE事件的流程:


InboundHandler、OutboundHandler类型的过滤
从图中我们可以看出,op_read事件作为入站事件,只会流经pipeline上的inboundhandler,具体的过滤handler的源码如下所示:
- Pipeline过滤inbound、outbound的handler
//遍历pipeline上的ctx链,直到找到一个inbound类型并返回
private AbstractChannelHandlerContext findContextInbound() {
AbstractChannelHandlerContext ctx = this;
do {
ctx = ctx.next;
} while (!ctx.inbound);
return ctx;
}
//遍历pipeline上的ctx链,直到找到一个outbound类型并返回
private AbstractChannelHandlerContext findContextOutbound() {
AbstractChannelHandlerContext ctx = this;
do {
ctx = ctx.prev;
} while (!ctx.outbound);
return ctx;
}
NioServerSocketChannel的pipeline链
上文我们看到了,默认的pipeline的创建以及事件的流经和handler的过滤,这里我们看一下当ServerBoostrap启动的时候,我们创建的用于accept客户端请求的NioServerSocketChannel的默认
的处理链都有哪些,首先根据之前的分析,默认的pipeline中包含head和tail,而在NioServerSocketChannel的初始化过程中又添加了ServerBootstrap$ServerBootstrapAcceptor,所以服务端Channel的
默认链为:Head->ServerBootstrap$ServerBootstrapAcceptor→Tail
相对应NioSocketChannel的处理链为:Head->自定义链->Tiail
网友评论