引言
上一篇文章介绍了Netty
的线程模型及EventLoop
机制,相信大家对Netty
已经有一个基本的认识。那么本篇文章我会根据Netty提供的Demo
来分析一下Netty
启动流程。
启动流程概览
开始之前,我们先来分析下Netty
服务端的启动流程,下面是一个简单的流程图

启动流程大致分为五步
- 创建
ServerBootstrap
实例,ServerBootstrap
是Netty服务端的启动辅助类,其存在意义在于其整合了Netty可以提供的所有能力,并且尽可能的进行了封装,以方便我们使用
- 设置并绑定
EventLoopGroup
,EventLoopGroup
其实是一个包含了多个EventLoop
的NIO线程池,在上一篇文章我们也有比较详细的介绍过EventLoop
事件循环机制,不过值得一提的是,Netty 中的EventLoop
不仅仅只处理IO读写事件,还会处理用户自定义或系统的Task任务
- 创建服务端Channel
NioServerSocketChannel
,并绑定至一个EventLoop
上。在初始化NioServerSocketChannel
的同时,会创建ChannelPipeline
,ChannelPipeline
其实是一个绑定了多个ChannelHandler
的执行链,后面我们会详细介绍
- 为服务端
Channel
添加并绑定ChannelHandler
,ChannelHandler
是Netty开放给我们的一个非常重要的接口,在触发网络读写事件后,Netty都会调用对应的ChannelHandler
来处理,后面我们会详细介绍
- 为服务端
Channel
绑定监听端口,完成绑定之后,Reactor线程(也就是第三步绑定的EventLoop线程)就开始执行Selector
轮询网络IO事件了,如果Selector
轮询到网络IO事件了,则会调用Channel
对应的ChannelPipeline
来依次执行对应的ChannelHandler
启动流程源码分析
下面我们就从启动源码来进一步分析 Netty 服务端的启动流程
入口
首先来看下常见的启动代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| 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) .option(ChannelOption.SO_BACKLOG, 100) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(serverHandler); } });
ChannelFuture f = b.bind(PORT).sync();
f.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); }
|
- 可以看到上面的代码首先创建了两个
EventLoopGroup
,在上一篇文章我们有介绍过Netty
的线程模型有三种,而不同的EventLoopGroup
配置对应了三种不同的线程模型。这里创建的两个EventLoopGroup
则是用了多线程Reactor模型
,其中bossEventLoopGroup
对应的就是处理Accept
事件的线程组,而workEventLoopGroup
则负责处理IO读写事件。
- 然后就是创建了一个启动辅助类
ServerBootstrap
,并且配置了如下几个重要参数
- group 两个Reactor线程组(bossEventLoopGroup, workEventLoopGroup)
- channel 服务端Channel
- option 服务端socket参数配置 例如
SO_BACKLOG
指定内核未连接的Socket连接排队个数
- handler 服务端Channel对应的Handler
- childHandler 客户端请求Channel对应的Handler
- 绑定服务端监听端口,启动服务 ->
ChannelFuture f = b.bind(PORT).sync();
这篇文章主要是分析Netty的启动流程。so我们直接看b.bind(PORT).sync()
的源码
bind
发现该方法内部实际调用的是doBind(final SocketAddress localAddress)
方法
doBind
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| private ChannelFuture doBind(final SocketAddress localAddress) {
final ChannelFuture regFuture = initAndRegister(); final Channel channel = regFuture.channel(); if (regFuture.cause() != null) { return regFuture; }
if (regFuture.isDone()) { ChannelPromise promise = channel.newPromise(); doBind0(regFuture, channel, localAddress, promise); return promise; } .... }
|
doBind
主要做了两个事情
initAndRegister()
初始化Channel
doBind0
绑定监听端口
initAndRegister()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| final ChannelFuture initAndRegister() { Channel channel = null; try { channel = channelFactory.newChannel(); init(channel); } catch (Throwable t) { ... } ChannelFuture regFuture = config().group().register(channel); if (regFuture.cause() != null) { if (channel.isRegistered()) { channel.close(); } else { channel.unsafe().closeForcibly(); } } return regFuture; }
|
channelFactory.newChannel()
其实就是通过反射创建配置的服务端Channel类,在这里是NioServerSocketChannel
创建完成的NioServerSocketChannel
进行一些初始化操作,例如将我们配置的Handler
加到服务端Channel
的pipeline
中
- 将
Channel
注册到EventLoopGroup
中一个EventLoop上
下面我们来看下NioServerSocketChannel
类的构造方法,看看它到底初始化了哪些东西,先看下其继承结构
NioServerSocketChannel初始化

下面是它的构造方法的调用顺序,依次分为了四步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| public NioServerSocketChannel() {
this(newSocket(DEFAULT_SELECTOR_PROVIDER)); }
public NioServerSocketChannel(ServerSocketChannel channel) { super(null, channel, SelectionKey.OP_ACCEPT); config = new NioServerSocketChannelConfig(this, javaChannel().socket()); }
protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) { super(parent); this.ch = ch; this.readInterestOp = readInterestOp; try { ch.configureBlocking(false); } catch (IOException e) { try { ch.close(); } catch (IOException e2) { logger.warn( "Failed to close a partially initialized socket.", e2); }
throw new ChannelException("Failed to enter non-blocking mode.", e); } }
protected AbstractChannel(Channel parent) { this.parent = parent; id = newId(); unsafe = newUnsafe(); pipeline = newChannelPipeline(); }
|
可以看到NioServerSocketChannel
的构造函数主要是初始化并绑定了以下3类
- 绑定一个Java
ServerSocketChannel
类
- 绑定一个
unsafe
类,unsafe封装了Netty底层的IO读写操作
- 绑定一个
pipeline
,每个Channel都会唯一绑定一个pipeline
init(Channel channel)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| void init(Channel channel) {
setChannelOptions(channel, newOptionsArray(), logger); setAttributes(channel, attrs0().entrySet().toArray(EMPTY_ATTRIBUTE_ARRAY));
ChannelPipeline p = channel.pipeline(); final EventLoopGroup currentChildGroup = childGroup; final ChannelHandler currentChildHandler = childHandler; final Entry<ChannelOption<?>, Object>[] currentChildOptions; synchronized (childOptions) { currentChildOptions = childOptions.entrySet().toArray(EMPTY_OPTION_ARRAY); } final Entry<AttributeKey<?>, Object>[] currentChildAttrs = childAttrs.entrySet().toArray(EMPTY_ATTRIBUTE_ARRAY); p.addLast(new ChannelInitializer<Channel>() { @Override public void initChannel(final Channel ch) { final ChannelPipeline pipeline = ch.pipeline(); ChannelHandler handler = config.handler(); if (handler != null) { pipeline.addLast(handler); } ch.eventLoop().execute(new Runnable() { @Override public void run() { pipeline.addLast(new ServerBootstrapAcceptor( ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs)); } }); } }); }
|
这里主要是为服务端Channel配置一些参数,以及对应的处理器ChannelHandler
,注意这里不仅仅会把我们自定义配置的ChannelHandler
加上去,同时还会自动帮我们加入一个系统Handler
(ServerBootstrapAcceptor
),这就是Netty用来接收客户端请求的Handler
,在ServerBootstrapAcceptor
内部会完成SocketChannel
的连接,EventLoop
的绑定等操作,之后我们会着重分析这个类
Channel的注册
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| public ChannelFuture register(Channel channel) {
return next().register(channel); }
public ChannelFuture register(Channel channel) { return register(new DefaultChannelPromise(channel, this)); }
public final void register(EventLoop eventLoop, final ChannelPromise promise) { ObjectUtil.checkNotNull(eventLoop, "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); } .... }
|
完成注册流程
- 完成实际的Java
ServerSocketChannel
与Select
选择器的绑定
- 并触发
channelRegistered
以及channelActive
事件
到这里为止,其实Netty服务端已经基本启动完成了,就差绑定一个监听端口了。可能读者会很诧异,怎么没有看到Nio线程轮询 IO事件的循环呢,讲道理肯定应该有一个死循环才对?那我们下面就把这段代码找出来
在之前的代码中,我们经常会看到这样一段代码
1 2 3 4 5 6 7
| eventLoop.execute(new Runnable() { @Override public void run() { ... } });
|
eventLoop.execute
到底做了什么事情?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| private void execute(Runnable task, boolean immediate) { boolean inEventLoop = inEventLoop(); addTask(task); if (!inEventLoop) { startThread(); ... } ... }
private void doStartThread() { assert thread == null; executor.execute(new Runnable() { @Override public void run() { thread = Thread.currentThread(); if (interrupted) { thread.interrupt(); }
boolean success = false; updateLastExecutionTime(); try { SingleThreadEventExecutor.this.run(); success = true; } catch (Throwable t) { logger.warn("Unexpected exception from an event executor: ", t); } finally { ... }
``` 通过上面的代码可以知道这里主要做了两件事情 1. 创建的任务被丢入了一个队列中等待执行 2. 如果是初次创建,则启动Nio线程 3. SingleThreadEventExecutor.this.run(); 调用子类的Run实现(执行IO事件的轮询) 看下 `NioEventLoop`的`Run`方法实现
```java protected void run() { int selectCnt = 0; for (;;) { try { int strategy; try { strategy = selectStrategy.calculateStrategy(selectNowSupplier, hasTasks()); ... default: } } catch (IOException e) { rebuildSelector0(); selectCnt = 0; handleLoopException(e); continue; } selectCnt++; cancelledKeys = 0; needsToSelectAgain = false; final int ioRatio = this.ioRatio; boolean ranTasks; if (ioRatio == 100) { try { if (strategy > 0) { processSelectedKeys(); } } finally { ranTasks = runAllTasks(); } } ... } } }
|
到这里的代码是不是就非常熟悉了,熟悉的死循环轮询事件
- 通过Selector来轮询IO事件
- 触发Channel所绑定的Handler处理对应的事件
- 处理完IO事件了 会执行系统或用户自定义加入的Task
doBind0
实际的Bind逻辑在 NioServerSocketChannel
中执行,我们直接省略前面一些冗长的调用,来看下最底层的调用代码,发现其实就是调用其绑定的Java Channel来执行对应的监听端口绑定逻辑
1 2 3 4 5 6 7 8
| protected void doBind(SocketAddress localAddress) throws Exception {
if (PlatformDependent.javaVersion() >= 7) { javaChannel().bind(localAddress, config.getBacklog()); } else { javaChannel().socket().bind(localAddress, config.getBacklog()); } }
|
尾言
本篇文章把Netty的启动流程粗略的捋了一遍,目的不是为了抠细节,而是大致能够清楚Netty服务端启动时主要做了哪些事情,所以有些地方难免会比较粗略一笔带过。在后面的文章我会把一些细节的源码单独拎出来深入分析