Pipeline是一个由HandlerContext节点构成的双向环形链表,结构如下图,最前面是HeadContext,末尾是TailContext中间是用户自定义的HandlerContext节点
先来看pipLine的构造参数
/**
* channelPipLine的默认构造方法
* @param channel
*/
protected DefaultChannelPipeline(Channel channel) {
this.channel = ObjectUtil.checkNotNull(channel, "channel");
succeededFuture = new SucceededChannelFuture(channel, null);
voidPromise = new VoidChannelPromise(channel, true);
//创建TailContext
tail = new TailContext(this);
//创建HeadContext
head = new HeadContext(this);
head.next = tail;
tail.prev = head;
}
可以看到pipline默认创建一个head和tail并且组成一个双向链表,而pipline的创建需要一个channel作为参数,实际上pipline是在channel里面创建的(即一个channel对应一个pipline)
pipline的添加节点方法
public final ChannelPipeline addLast(ChannelHandler handler) {
return addLast(null, handler);
}
最终调用到
@Override
public final ChannelPipeline addLast(EventExecutorGroup group, String name, ChannelHandler handler) {
final AbstractChannelHandlerContext newCtx;
synchronized (this) {
//检查handler是否重复添加
checkMultiplicity(handler);
//创建pipLine节点
newCtx = newContext(group, filterName(name, handler), handler);
//添加节点操作
addLast0(newCtx);
if (!registered) {
newCtx.setAddPending();
callHandlerCallbackLater(newCtx, true);
return this;
}
EventExecutor executor = newCtx.executor();
//判断当前线程是否是NioEventLoop运行线程
if (!executor.inEventLoop()) {
newCtx.setAddPending();
executor.execute(new Runnable() {
@Override
public void run() {
//调用hander的add方法
callHandlerAdded0(newCtx);
}
});
return this;
}
}
callHandlerAdded0(newCtx);
return this;
}
- 检查handler是否重复添加
- 创建pipLine节点<