2021SC@SDUSC
Netty 接受请求过程源码剖析 1 源码剖析目的-
服务器启动后肯定是要接受客户端请求并返回客户端想要的信息的,下面源码分析 Netty 在启动之后是如何接受客户端请求的
-
在 io.netty.example 包 下
说明:
-
从之前服务器启动的源码中,我们得知,服务器最终注册了一个 Accept 事件等待客户端的连接。我们也知道,
NioServerSocketChannel 将自己注册到了 boss 单例线程池(reactor 线程)上,也就是 EventLoop 。 -
先简单说下 EventLoop 的逻辑(后面我们详细讲解 EventLoop)
EventLoop 的作用是一个死循环,而这个循环中做 3 件事情:
- 有条件的等待 Nio 事件。
- 处理 Nio 事件。
- 处理消息队列中的任务。
仍用前面的项目来分析:进入到 NioEventLoop 源码中后,在 private void processSelectedKey(SelectionKey k,AbstractNioChannel ch) 方法开始调试最终我们要分析到 AbstractNioChannel 的 doBeginRead 方法, 当到这个方法时,针对于这个客户端的连接就完成了,接下来就可以监听读事件了
3 源码分析过程
## 1.断点位置 NioEventLoop 的如下方法 processSelectedKey
if ((readyOps & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0 || readyOps == 0) { unsafe.read(); //断点位置
}
## 2.执行 浏览器 http://localhost:8007/, 客户端发出请求
## 3.从的断点我们可以看到, readyOps 是 16 ,也就是 Accept 事件。说明浏览器的请求已经进来了。
## 4.这个 unsafe 是 boss 线程中 NioServerSocketChannel 的 AbstractNioMessageChannel$NioMessageUnsafe 对象。我们进入到 AbstractNioMessageChannel$NioMessageUnsafe 的 read 方法中
## 5.read 方法代码并分析:
@Override
public void read() {
assert eventLoop().inEventLoop(); final ChannelConfig config = config();
final ChannelPipeline pipeline = pipeline();
final RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle(); allocHandle.reset(config);
boolean closed = false; Throwable exception = null; try {
try {
do {
int localRead = doReadMessages(readBuf); if (localRead == 0) {
break;
}
if (localRead < 0) { closed = true; break;
}
allocHandle.incMessagesRead(localRead);
} while (allocHandle.continueReading());
} catch (Throwable t) { exception = t;
}
int size = readBuf.size();
for (int i = 0; i < size; i ++) { readPending = false;
pipeline.fireChannelRead(readBuf.get(i));
}
readBuf.clear(); allocHandle.readComplete(); pipeline.fireChannelReadComplete();
if (exception != null) {
closed = closeOnReadError(exception);
pipeline.fireExceptionCaught(exception);
}
if (closed) {
inputShutdown = true; if (isOpen()) {
close(voidPromise());
}
}
method
} finally {
// Check if there is a readPending which was not processed yet.
// This could be for two reasons:
// * The user called Channel.read() or ChannelHandlerContext.read() in channelRead(...) method
// * The user called Channel.read() or ChannelHandlerContext.read() in channelReadComplete(...)
//
// See https://github.com/netty/netty/issues/2254 if (!readPending && !config.isAutoRead()) {
removeReadOp();
}
}
}
说明:
1)检查该 eventloop 线程是否是当前线程。assert eventLoop().inEventLoop()
2)执行 doReadMessages 方法,并传入一个 readBuf 变量,这个变量是一个 List,也就是容器。
3)循环容器,执行 pipeline.fireChannelRead(readBuf.get(i));
4)doReadMessages 是读取 boss 线程中的 NioServerSocketChannel 接受到的请求。并把这些请求放进容器,
一会我们 debug 下 doReadMessages 方法.
5) 循环遍历 容器中的所有请求,调用 pipeline 的 fireChannelRead 方法,用于处理这些接受的请求或者其他事件,在 read 方法中,循环调用 ServerSocket 的 pipeline 的 fireChannelRead 方法, 开始执行 管道中的
handler 的 ChannelRead 方法(debug 进入)
## 6.追踪一下 doReadMessages 方法, 就可以看得更清晰
protected int doReadMessages(List
1.Netty抽象出两组线程池BossGroup专门负责接收客户端的连接,WorkerGroup专门负责网络的读写
2.BossGroup和,WorkerGroup 对应的类型都是NioEventLoopGroup
3.NioEventLoopGroup相当于一个事件循环组,这个组中含有多个事件循环,每一个事件循环是NioEventLoop
4.NioEventLoop表示一个不断循环的执行处理任务的线程,每个NioEventLoop都有一个selector,用于监听绑定在其上的socket的网络通讯
5.NioEventLoopGroup可以有多个线程,即可以含有多个NioEventLoop
6.每个Boss NioEventLoop循环执行的步骤有三步:
1.轮询accept事件 2.处理accept事件,与client建立连接,生成一个NioSocketChannle,并将其注册到某个worker NioEventLoop上的selector 3.处理任务队列的任务,即runAllTasks
7.每个worker的NioEventLoop 循环执行的步骤:
1.轮询read write事件 2.处理IO事件,即read ,write,在对应的NioSocketChannel处理 3.处理任务队列的任务,即runAllTasks
8.每个worker的NioEventLoop处理业务时,会使用pipeline(管道),pipeline中包含了channel,即通过pipeline可以获取到对应通道,管道中维护了很多的处理器



