初始化channelPipeLine ChannelPipeline p = channel.pipeline();
p.addLast(new ChannelInitializer<Channel>() {1--1
public void initChannel(final Channel ch) throws Exception {
final ChannelPipeline pipeline = ch.pipeline();
ChannelHandler handler = config.handler();
if (handler != null) {
pipeline.addLast(handler);
}
ch.eventLoop().execute(new Runnable() {
public void run() {
pipeline.addLast(new ServerBootstrapAcceptor(
ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
}
});
}
});
2--2
public final ChannelPipeline addLast(EventExecutorGroup group, String name, ChannelHandler handler) {
final AbstractChannelHandlerContext newCtx;
synchronized (this) {
checkMultiplicity(handler);
//创建新的ChannelHandlerContext==new ChannelInitializer<Channel>() {}
newCtx = newContext(group, filterName(name, handler), handler);
//channel 还没有注册 ,将newCtx加入职责链(DefaultChannelPipeline)中
addLast0(newCtx);
//判断此 channel是否被注册
if (!registered) {
newCtx.setAddPending();
//如果没有注册加入任务队列中 等注册完成后在调用执行任务 3--3开始调用此任务
callHandlerCallbackLater(newCtx, true);
return this;
}
EventExecutor executor = newCtx.executor();
//判断是否是本线程操作
if (!executor.inEventLoop()) {
//如果不是将异步执行添加
callHandlerAddedInEventLoop(newCtx, executor);
return this;
}
}
//本线程则直接添加
callHandlerAdded0(newCtx);
return this;
}
//Channel注册成功后调用 DefaultChannelPipeline.invokeHandlerAddedIfNeeded()
AbstractChannel.java -->register0(ChannelPromise promise)-->pipeline.invokeHandlerAddedIfNeeded()
3--3
final void invokeHandlerAddedIfNeeded() {
//判断是否注册
if (firstRegistration) {
firstRegistration = false;
callHandlerAddedForAllHandlers();
}
}
4--4 执行在注册前创建的默认职责链 DefaultChannelPipeline.callHandlerAddedForAllHandlers()
private void callHandlerAddedForAllHandlers() {
final PendingHandlerCallback pendingHandlerCallbackHead;
synchronized (this) {
assert !registered;
registered = true;
pendingHandlerCallbackHead = this.pendingHandlerCallbackHead;
this.pendingHandlerCallbackHead = null;
}
PendingHandlerCallback task = pendingHandlerCallbackHead;
while (task != null) {
task.execute(); 开始调用 initChannel(final Channel ch)
task = task.next;
}
}