在上一篇文章里我们主要介绍了 tomcat io 线程中涉及到的主要核心类,包括 AbstractProcessorLight,Http11Processor,CoyoteAdapter,这里主要介绍对于请求数据的读取。
对于 tomcat 请求数据的读取来说,可以分为请求行的读取,请求头的读取,请求体的读取,三个部分方法调用序列图如下:
读取请求行
读取请求头
读取请求体
综合上面三个序列图,对于请求行,请求头,请求体的读取都最终调用了NioSocketWrapper 对象实例的 fillReadBuffer() 方法。只不过请求行和请求头读取参数传递为 true,请求体读取参数传递为 false,该方法核心代码如下:
private int fillReadBuffer(boolean block, ByteBuffer to) throws IOException {
int nRead;
NioChannel socket = getSocket();
if (socket instanceof ClosedNioChannel) {
throw new ClosedChannelException();
}
if (block) {
Selector selector = null;
try {
selector = pool.get();
} catch (IOException x) {
// Ignore
}
try {
nRead = pool.read(to, socket, selector, getReadTimeout());
} finally {
if (selector != null) {
pool.put(selector);
}
}
} else {
nRead = socket.read(to);
if (nRead == -1) {
throw new EOFException();
}
}
return nRead;
}
//NioChannel
protected SocketChannel sc
public int read(ByteBuffer dst) throws IOException {
return sc.read(dst);
}
根据上述代码,请求行和请求头的读取本质是调用 java NIO api SocketChannel 的 read() 方法,该方法为非阻塞方法。如果读不到数据就直接返回,继续由以前文章介绍的 poller 线程监测是否有数据可读。
对于请求体的读取采用阻塞的方式,调用以前文章中介绍的 NioSelectorPool 的read(ByteBuffer buf, NioChannel socket, Selector selector, long readTimeout) 方法。在该方法中又会调用 NioBlockingSelector 的 read() 方法,核心代码如下:
根据以上代码整个读数据逻辑在一个循环里进行,如果有数据读到就跳出循环,返回数据。
如果没有数据,则调用 BlockPoller 的 add() 方法,该方法将封装的 OP_READ 事件添加到 BlockPoller 的事件队列里。关于 BlockPoller 我们在后面文章里详细讲解。
然后在调用以前文章介绍的 NioSocketWrapper 中的 CountDownLatch 类型 readLatch 属性的 await() 方法,使当前线程(一般是tomcat io线程)在 readLatch 上等待。
当前线程在 readLatch 上等待一般有超时时间(读超时时间),默认不配置为 -1,这时超时时间为 Long.MAX_VALUE 毫秒。
对于 tomcat 数据读取总结如下: