Netty服务端启动流程

Catalogue
  1. 两个线程组
  2. 引导程序

两个线程组

1
2
EventLoopGroup boosGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();

EventLoopGroup的定义

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
public class NioEventLoopGroup extends MultithreadEventLoopGroup{
/**
* Sets the percentage of the desired amount of time spent for I/O in the child event loops. The default value is
* {@code 50}, which means the event loop will try to spend the same amount of time for I/O as for non-I/O tasks.
*/
public void setIoRatio(int ioRatio) {
for (EventExecutor e: children()) {
((NioEventLoop) e).setIoRatio(ioRatio);
}
}
/**
* Replaces the current {@link Selector}s of the child event loops with newly created {@link Selector}s to work
* around the infamous epoll 100% CPU bug.
*/
public void rebuildSelectors() {
for (EventExecutor e: children()) {
((NioEventLoop) e).rebuildSelector();
}
}

@Override
protected EventExecutor newChild(ThreadFactory threadFactory, Object... args) throws Exception {
return new NioEventLoop(this, threadFactory, (SelectorProvider) args[0],
((SelectStrategyFactory) args[1]).newSelectStrategy(), (RejectedExecutionHandler) args[2]);
}
}

专门用于处理网络的事件

一个用于处理接受客户端的连接,一个用于进行 SocketChannel 的网络读取。

boos这个EventLoopGroup作为一个acceptor负责接收来自客户端的请求,然后分发给worker这个EventLoopGroup来处理所有的事件event和channel的IO。

引导程序

ServerBootstrap. 启动NIO服务的辅助启动类.

1
2
3
4
5
6
7
8
ServerBootstrap b = new ServerBootstrap()
.group(boosGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1012)
.childHandler(new ChildChannelHandler());

ChannelFuture f = b.bind(port).sync(); // 绑定端口
f.channel().closeFuture().sync();// 等待服务器端监听端口关闭
    1. group方法绑定了两个NIO线程组
    1. 绑定处理消息的Handler. handler处理流程和管理流程-TODO