Netty 服务端启动

Netty 服务端启动大致流程

process.jpg

newChannel阶段

通过AbstractBootstrap#channel进行设置,最后通过Java的反射生成Channel,代码块如下:

public B channel(Class<? extends C> channelClass) {  
    if (channelClass == null) {  
        throw new NullPointerException("channelClass");  
  }  
    return channelFactory(new ReflectiveChannelFactory<C>(channelClass));  
}

ReflectiveChannelFactory#newChannel

public ReflectiveChannelFactory(Class<? extends T> clazz) {  
    if (clazz == null) {  
        throw new NullPointerException("clazz");  
  }  
    this.clazz = clazz;  
}  
@Override  
public T newChannel() {  
    try {  
        return clazz.newInstance();   // 通过反射
  } catch (Throwable t) {  
        throw new ChannelException("Unable to create Channel from class " + clazz, t);  
  }  
}

init 阶段

主要参数是参数和属性设置

@Override  
void init(Channel channel) throws Exception {  
     // set Options
     //  set Attrs 

    ChannelPipeline p = channel.pipeline();  
    final EventLoopGroup currentChildGroup = childGroup;  
    final ChannelHandler currentChildHandler = childHandler;  
    final Entry<ChannelOption<?>, Object>[] currentChildOptions;  
    final Entry<AttributeKey<?>, Object>[] currentChildAttrs;  
    synchronized (childOptions) {  
            currentChildOptions = childOptions.entrySet().toArray(newOptionArray(childOptions.size()));  
    }  
    synchronized (childAttrs) {  
        currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(childAttrs.size()));  
    }  
    p.addLast(new ChannelInitializer<Channel>() {  
        @Override  
        public void initChannel(Channel ch) throws Exception {  
            final ChannelPipeline pipeline = ch.pipeline();  
            ChannelHandler handler = config.handler();  
            if (handler != null) {  
                pipeline.addLast(handler);  
            }  
            // We add this handler via the EventLoop as the user may have used a ChannelInitializer as handler.  
            // In this case the initChannel(...) method will only be called after this method returns. Because // of this we need to ensure we add our handler in a delayed fashion so all the users handler are // placed in front of the ServerBootstrapAcceptor. 
            ch.eventLoop().execute(new Runnable() {  
                            @Override  
                    public void run() {  
                          pipeline.addLast(new ServerBootstrapAcceptor(currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));  
                        }  
                });  
         }  
    });  
}

register 阶段

注册Channel事件

@Override
protected void doRegister() throws Exception {
    boolean selected = false;
    for (;;) {
        try {
            // interestOps为0, 不监听任何事件。
            selectionKey = javaChannel().register(eventLoop().selector, 0, this);
            return;
        } catch (CancelledKeyException e) {
            if (!selected) {
                // Force the Selector to select now as the "canceled" SelectionKey may still be
                // cached and not removed because no Select.select(..) operation was called yet.
                eventLoop().selectNow();
                selected = true;
            } else {
                // We forced a select operation on the selector before but the SelectionKey is still cached
                // for whatever reason. JDK bug ?
                throw e;
            }
        }
    }
}

doBind阶段

端口绑定

@Override  
protected void doBind(SocketAddress localAddress) throws Exception {  
    if (PlatformDependent.javaVersion() >= 7) {  
        javaChannel().bind(localAddress, config.getBacklog());  
  } else {  
        javaChannel().socket().bind(localAddress, config.getBacklog());  
  }  
}
添加新评论