ServerBootstrap与Bootstrap分别是netty中服务端与客户端的引导类,主要负责服务端与客户端初始化、配置及启动引导等工做,接下来咱们就经过netty源码中的示例对ServerBootstrap与Bootstrap的源码进行一个简单的分析。首先咱们知道这两个类都继承自AbstractBootstrap类java
接下来咱们就经过netty源码中ServerBootstrap的实例入手对其进行一个简单的分析。git
// Configure the server.
EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); final EchoServerHandler serverHandler = new EchoServerHandler(); try { //初始化一个服务端引导类
ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) //设置线程组
.channel(NioServerSocketChannel.class)//设置ServerSocketChannel的IO模型 分为epoll与Nio
.option(ChannelOption.SO_BACKLOG, 100)//设置option参数,保存成一个LinkedHashMap<ChannelOption<?>, Object>()
.handler(new LoggingHandler(LogLevel.INFO))//这个hanlder 只专属于 ServerSocketChannel 而不是 SocketChannel。
.childHandler(new ChannelInitializer<SocketChannel>() { //这个handler 将会在每一个客户端链接的时候调用。供 SocketChannel 使用。
@Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); } //p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(serverHandler); } }); // Start the server. 启动服务
ChannelFuture f = b.bind(PORT).sync(); // Wait until the server socket is closed.
f.channel().closeFuture().sync(); } finally { // Shut down all event loops to terminate all threads.
bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); }
接下来咱们主要从服务端的socket在哪里初始化与哪里accept链接这两个问题入手对netty服务端启动的流程进行分析;github
咱们首先要知道,netty服务的启动其实能够分为如下四步:promise
1、建立服务端Channelapp
一、服务端Channel的建立,主要为如下流程异步
咱们经过跟踪代码可以看到socket
final ChannelFuture regFuture = initAndRegister();// 初始化并建立 NioServerSocketChannel
咱们在initAndRegister()中能够看到channel的初始化。tcp
channel = channelFactory.newChannel(); // 经过 反射工厂建立一个 NioServerSocketChannel
我进一步看newChannel()中的源码,在ReflectiveChannelFactory这个反射工厂中,经过clazz这个类的反射建立了一个服务端的channel。ide
@Override public T newChannel() { try { return clazz.getConstructor().newInstance();//反射建立 } catch (Throwable t) { throw new ChannelException("Unable to create Channel from class " + clazz, t); } }
既然经过反射,咱们就要知道clazz类是什么,那么我咱们来看下channelFactory这个工厂类是在哪里初始化的,初始化的时候咱们传入了哪一个channel。函数
这里咱们须要看下demo实例中初始化ServerBootstrap时.channel(NioServerSocketChannel.class)这里的具体实现,咱们看下源码
public B channel(Class<? extends C> channelClass) { if (channelClass == null) { throw new NullPointerException("channelClass"); } return channelFactory(new ReflectiveChannelFactory<C>(channelClass)); }
经过上面的代码我能够直观的看出正是在这里咱们经过NioServerSocketChannel这个类构造了一个反射工厂。
那么到这里就很清楚了,咱们建立的Channel就是一个NioServerSocketChannel,那么具体的建立咱们就须要看下这个类的构造函数。首先咱们看下一个NioServerSocketChannel建立的具体流程
首先是newsocket(),咱们先看下具体的代码,在NioServerSocketChannel的构造函数中咱们建立了一个jdk原生的ServerSocketChannel
/** * Create a new instance */ public NioServerSocketChannel() { this(newSocket(DEFAULT_SELECTOR_PROVIDER));//传入默认的SelectorProvider } private static ServerSocketChannel newSocket(SelectorProvider provider) { try { /** * Use the {@link SelectorProvider} to open {@link SocketChannel} and so remove condition in * {@link SelectorProvider#provider()} which is called by each ServerSocketChannel.open() otherwise. * * See <a href="https://github.com/netty/netty/issues/2308">#2308</a>. */ return provider.openServerSocketChannel();//能够看到建立的是jdk底层的ServerSocketChannel } catch (IOException e) { throw new ChannelException( "Failed to open a server socket.", e); } }
第二步是经过NioServerSocketChannelConfig配置服务端Channel的构造函数,在代码中咱们能够看到咱们把NioServerSocketChannel这个类传入到了NioServerSocketChannelConfig的构造函数中进行配置
/** * Create a new instance using the given {@link ServerSocketChannel}. */ public NioServerSocketChannel(ServerSocketChannel channel) { super(null, channel, SelectionKey.OP_ACCEPT);//调用父类构造函数,传入建立的channel config = new NioServerSocketChannelConfig(this, javaChannel().socket()); }
第三步在父类AbstractNioChannel的构造函数中把建立服务端的Channel设置为非阻塞模式
/** * Create a new instance * * @param parent the parent {@link Channel} by which this instance was created. May be {@code null} * @param ch the underlying {@link SelectableChannel} on which it operates * @param readInterestOp the ops to set to receive data from the {@link SelectableChannel} */ protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) { super(parent); this.ch = ch;//这个ch就是传入的经过jdk建立的Channel this.readInterestOp = readInterestOp; try { ch.configureBlocking(false);//设置为非阻塞 } catch (IOException e) { try { ch.close(); } catch (IOException e2) { if (logger.isWarnEnabled()) { logger.warn( "Failed to close a partially initialized socket.", e2); } } throw new ChannelException("Failed to enter non-blocking mode.", e); } }
第四步调用AbstractChannel这个抽象类的构造函数设置Channel的id(每一个Channel都有一个id,惟一标识),unsafe(tcp相关底层操做),pipeline(逻辑链)等,而无论是服务的Channel仍是客户端的Channel都继承自这个抽象类,他们也都会有上述相应的属性。咱们看下AbstractChannel的构造函数
/** * Creates a new instance. * * @param parent * the parent of this channel. {@code null} if there's no parent. */ protected AbstractChannel(Channel parent) { this.parent = parent; id = newId();//建立Channel惟一标识 unsafe = newUnsafe();//netty封装的TCP 相关操做类 pipeline = newChannelPipeline();//逻辑链 }
二、初始化服务端建立的Channel
init(channel);// 初始化这个 NioServerSocketChannel
咱们首先列举下init(channel)中具体都作了哪了些功能:
那么接下来咱们经过代码,对每一步设置进行一下分析:
首先是在SeverBootstrap的init()方法中对ChannelOptions、ChannelAttrs 的配置的关键代码
final Map<ChannelOption<?>, Object> options = options0();//拿到你设置的option synchronized (options) { setChannelOptions(channel, options, logger);//设置NioServerSocketChannel相应的TCP参数,其实这一步就是把options设置到channel的config中 } final Map<AttributeKey<?>, Object> attrs = attrs0(); synchronized (attrs) { for (Entry<AttributeKey<?>, Object> e: attrs.entrySet()) { @SuppressWarnings("unchecked") AttributeKey<Object> key = (AttributeKey<Object>) e.getKey(); channel.attr(key).set(e.getValue()); } }
而后是对ChildOptions、ChildAttrs配置的关键代码
//能够看到两个都是局部变量,会在下面设置pipeline时用到 final Entry<ChannelOption<?>, Object>[] currentChildOptions; final Entry<AttributeKey<?>, Object>[] currentChildAttrs; synchronized (childOptions) { currentChildOptions = childOptions.entrySet().toArray(newOptionArray(0)); } synchronized (childAttrs) { currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(0)); }
第三步对服务端Channel的handler进行配置
p.addLast(new ChannelInitializer<Channel>() { @Override public void initChannel(final Channel ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); ChannelHandler handler = config.handler();//拿到咱们自定义的hanler if (handler != null) { pipeline.addLast(handler); } ch.eventLoop().execute(new Runnable() { @Override public void run() { pipeline.addLast(new ServerBootstrapAcceptor( ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs)); } }); } });
第四步添加ServerBootstrapAcceptor链接器,这个是netty向服务端Channel自定义添加的一个handler,用来处理新链接的添加与属性配置,咱们来看下关键代码
ch.eventLoop().execute(new Runnable() { @Override public void run() { //在这里会把咱们自定义的ChildGroup、ChildHandler、ChildOptions、ChildAttrs相关配置传入到ServerBootstrapAcceptor构造函数中,并绑定到新的链接上 pipeline.addLast(new ServerBootstrapAcceptor( ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs)); } });
3、注册Selector
一个服务端的Channel建立完毕后,下一步就是要把它注册到一个事件轮询器Selector上,在initAndRegister()中咱们把上面初始化的Channel进行注册
ChannelFuture regFuture = config().group().register(channel);//注册咱们已经初始化过的Channel
而这个register具体实现是在AbstractChannel中的AbstractUnsafe抽象类中的
/** * 一、先是一系列的判断。 * 二、判断当前线程是不是给定的 eventLoop 线程。注意:这点很重要,Netty 线程模型的高性能取决于对于当前执行的Thread 的身份的肯定。若是不在当前线程,那么就须要不少同步措施(好比加锁),上下文切换等耗费性能的操做。 * 三、异步(由于咱们这里直到如今仍是 main 线程在执行,不属于当前线程)的执行 register0 方法。 */ @Override public final void register(EventLoop eventLoop, final ChannelPromise promise) { if (eventLoop == null) { throw new NullPointerException("eventLoop"); } if (isRegistered()) { promise.setFailure(new IllegalStateException("registered to an event loop already")); return; } if (!isCompatible(eventLoop)) { promise.setFailure( new IllegalStateException("incompatible event loop type: " + eventLoop.getClass().getName())); return; } AbstractChannel.this.eventLoop = eventLoop;//绑定线程 if (eventLoop.inEventLoop()) { register0(promise);//实际的注册过程 } else { try { eventLoop.execute(new Runnable() { @Override public void run() { register0(promise); } }); } catch (Throwable t) { logger.warn( "Force-closing a channel whose registration task was not accepted by an event loop: {}", AbstractChannel.this, t); closeForcibly(); closeFuture.setClosed(); safeSetFailure(promise, t); } } }
首先咱们对整个注册的流程作一个梳理
接下来咱们进入register0()方法看下注册过程的具体实现
private void register0(ChannelPromise promise) { try { // check if the channel is still open as it could be closed in the mean time when the register // call was outside of the eventLoop if (!promise.setUncancellable() || !ensureOpen(promise)) { return; } boolean firstRegistration = neverRegistered; doRegister();//jdk channel的底层注册 neverRegistered = false; registered = true; // 触发绑定的handler事件 // Ensure we call handlerAdded(...) before we actually notify the promise. This is needed as the // user may already fire events through the pipeline in the ChannelFutureListener. pipeline.invokeHandlerAddedIfNeeded(); safeSetSuccess(promise); pipeline.fireChannelRegistered(); // Only fire a channelActive if the channel has never been registered. This prevents firing // multiple channel actives if the channel is deregistered and re-registered. if (isActive()) { if (firstRegistration) { pipeline.fireChannelActive(); } else if (config().isAutoRead()) { // This channel was registered before and autoRead() is set. This means we need to begin read // again so that we process inbound data. // // See https://github.com/netty/netty/issues/4805 beginRead(); } } } catch (Throwable t) { // Close the channel directly to avoid FD leak. closeForcibly(); closeFuture.setClosed(); safeSetFailure(promise, t); } }
AbstractNioChannel中doRegister()的具体实现就是把jdk底层的channel绑定到eventLoop的selecor上
@Override protected void doRegister() throws Exception { boolean selected = false; for (;;) { try { //把channel注册到eventLoop上的selector上 selectionKey = javaChannel().register(eventLoop().unwrappedSelector(), 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; } } } }
到这里netty就把服务端的channel注册到了指定的selector上,下面就是服务端口的绑定
3、端口绑定
首先咱们梳理下netty中服务端口绑定的流程
咱们来看下AbstarctUnsafe中bind()方法的具体实现
@Override public final void bind(final SocketAddress localAddress, final ChannelPromise promise) { assertEventLoop(); if (!promise.setUncancellable() || !ensureOpen(promise)) { return; } // See: https://github.com/netty/netty/issues/576 if (Boolean.TRUE.equals(config().getOption(ChannelOption.SO_BROADCAST)) && localAddress instanceof InetSocketAddress && !((InetSocketAddress) localAddress).getAddress().isAnyLocalAddress() && !PlatformDependent.isWindows() && !PlatformDependent.maybeSuperUser()) { // Warn a user about the fact that a non-root user can't receive a // broadcast packet on *nix if the socket is bound on non-wildcard address. logger.warn( "A non-root user can't receive a broadcast packet if the socket " + "is not bound to a wildcard address; binding to a non-wildcard " + "address (" + localAddress + ") anyway as requested."); } boolean wasActive = isActive();//判断绑定是否完成 try { doBind(localAddress);//底层jdk绑定端口 } catch (Throwable t) { safeSetFailure(promise, t); closeIfClosed(); return; } if (!wasActive && isActive()) { invokeLater(new Runnable() { @Override public void run() { pipeline.fireChannelActive();//触发ChannelActive事件 } }); } safeSetSuccess(promise); }
在doBind(localAddress)中netty实现了jdk底层端口的绑定
@Override protected void doBind(SocketAddress localAddress) throws Exception { if (PlatformDependent.javaVersion() >= 7) { javaChannel().bind(localAddress, config.getBacklog()); } else { javaChannel().socket().bind(localAddress, config.getBacklog()); } }
在 pipeline.fireChannelActive()中会触发pipeline中的channelActive()方法
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.fireChannelActive(); readIfIsAutoRead(); }
在channelActive中首先会把ChannelActive事件往下传播,而后调用readIfIsAutoRead()方法出触发channel的read事件,而它最终调用AbstractNioChannel中的doBeginRead()方法
@Override protected void doBeginRead() throws Exception { // Channel.read() or ChannelHandlerContext.read() was called final SelectionKey selectionKey = this.selectionKey; if (!selectionKey.isValid()) { return; } readPending = true; final int interestOps = selectionKey.interestOps(); if ((interestOps & readInterestOp) == 0) { selectionKey.interestOps(interestOps | readInterestOp);//readInterestOp为 SelectionKey.OP_ACCEPT } }
在doBeginRead()方法,netty会把accept事件注册到Selector上。
到此咱们对netty服务端的启动流程有了一个大体的了解,总体能够归纳为下面四步:
一、channelFactory.newChannel(),其实就是建立jdk底层channel,并初始化id、piepline等属性;
二、init(channel),添加option、attr等属性,并添加ServerBootstrapAcceptor链接器;
三、config().group().register(channel),把jdk底层的channel注册到eventLoop上的selector上;
四、doBind0(regFuture, channel, localAddress, promise),完成服务端端口的监听,并把accept事件注册到selector上;
以上就是对netty服务端启动流程进行的一个简单分析,有不少细节没有关注与深刻,其中若有不足与不正确的地方还望指出与海涵。