ChannelPipeline| ChannelHandler| ChannelHandlerContext 创建过程
分为 3 个步骤来看创建的过程:
- 任何一个ChannelSocket 创建的同时都会创建 一个 pipeline
- 当用户或系统内部调用pipeline 的 add*** 方法添加 handler 时,都会创建一个包装这handler的Context
- 这些Context在pipeline中组成了双向链表。
在 SocketChannel 的抽象父类 AbstractChannel 的构造方法中
protected AbstractChannel(Channel parent) {
this.parent = parent;
id = newId();
unsafe = newUnsafe();
pipeline = newChannelPipeline();
}
Debug 一下,可以看到代码会执行到这里,然后继续追踪到
protected DefaultChannelPipeline(Channel channel) {
this.channel = ObjectUtil.checkNotNull(channel, "channel");
succeededFuture = new SucceededChannelFuture(channel, null);
voidPromise = new VoidChannelPromise(channel, true);
tail = new TailContext(this);
head = new HeadContext(this);
head.next = tail;
tail.prev = head;
}
说明:
- 将 channel 赋值给 channel 字段,用于 pipeline 操作 channel。
- 创建一个 future 和 promise,用于异步回调使用。
- 创建一个 inbound的tailContext,创建一个既是inbound类型又是 outbound 类型的 headContext.
- 最后,将两个Context互相连接,形成双向链表
- tailContext 和HeadContext 非常的重要,所有 pipeline 中的事件都会流经他们
- 在 add** 添加处理器的时候创建 Context**
-
看下 DefaultChannelPipeline 的 addLast 方法如何创建的 Context,代码如下
-
@Override
public final ChannelPipeline addLast(EventExecutorGroup executor, ChannelHandler... handlers){
if (handlers == null) {
//断点
throw new NullPointerException("handlers");
}
for (ChannelHandler h: handlers){
if(h == null){
break;
}
addlast(executor, null, h);
}
return this;
}
继续 Debug
@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;
}
说明
1) pipeline 添加 handler,参数是线程池,name是null,handler是我们或者系统传入的 handler。Netty 为了防上多个线程导致安全问题,同步了这段代码,步骤如下:
2) 检查这个handler实例是否是共享的,如果不是,并且已经被别的 pipeline 使用了,则抛出异常。调用 newContext(group, filterName(name, handler), handler) 方法,创建一个 Context。
3)从这里可以看出来了,每次添加一个 handler 都会创建一个关联 Context。
4)调用 addLast0 方法,将 Context 追加到链表中
5)如果这个通道还没有注册到 selector 上,就将这个 Context 添加到这个 pipeline 的待办任务中。当注册好了以后,就会调用 callHandlerAdded0 方法(默认是什么都不做,用户可以实现这个方法)。