Tomcat源码分析(二)------ 一次完整请求的里里外外 (转)
前几天分析了一下Tomcat的架构和启动过程,今天开始研究它的运转机制。Tomcat最本质就是个能运行JSP/Servlet的Web服务器 ,因此最典型的应用就是用户通过浏览器访问服务器,Tomcat接收到请求后转发给Servlet,由Servlet处理完后,把结果返回给客户端。今天就专门解析一下这么一个完整的请求的内部机理。
通过DEBUG,一路跟下来,发现Tomcat处理请求的核心过程是以下几点:
启动的时候启动预支持协议的Endpoint,Endpoint会起专门的线程监听相应协议的请求,默认的情况下,会启动JIoEndpoint,JIoEndpoint基于Java ServerSocket接收Http的请求
ServerSocket接收到客户端请求的Socket后,一路包装,并一路从Host一直传递到Wrapper,再请求到相应的Servlet
下面将重点解析以上两个过程。
通过以前的分析(Tomcat源码分析一)可知道当Tomcat启动的时候会启动Connector,此时Connector会通过ProtocolHandler把Endpoint启动起来。默认情况下,Tomcat会启动两种Connector,分别是Http协议和AJP协议的,依次对应Http11Protocol和AjpProtocol,两者都是启动JIoEndpoint。下面看看JIoEndpoint的start方法:
public void start() throws Exception {
// Initialize socket if not done before
if (!initialized) {
init();
}
if (!running) {
running = true;
paused = false;
// Create worker collection
if (getExecutor() == null) {
createExecutor();
}
// Start acceptor threads
for (int i = 0; i < acceptorThreadCount; i++) {
Thread acceptorThread = new Thread(new Acceptor(), getName() + "-Acceptor-" + i);
acceptorThread.setPriority(threadPriority);
acceptorThread.setDaemon(getDaemon());
acceptorThread.start();
}
}
}
public void start() throws Exception {
// Initialize socket if not done before
if (!initialized) {
init();
}
if (!running) {
running = true;
paused = false;
// Create worker collection
if (getExecutor() == null) {
createExecutor();
}
// Start acceptor threads
for (int i = 0; i < acceptorThreadCount; i++) {
Thread acceptorThread = new Thread(new Acceptor(), getName() + "-Acceptor-" + i);
acceptorThread.setPriority(threadPriority);
acceptorThread.setDaemon(getDaemon());
acceptorThread.start();
}
}
}
以上代码很清晰地表示启动acceptorThreadCount个线程,每个线程由Acceptor代理,具体看看Acceptor的run方法:
public void run() { // Loop until we receive a shutdown command while (running) { // Loop if endpoint is paused while (paused) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore } } // Accept the next incoming connection from the server socket try { Socket socket = serverSocketFactory.acceptSocket(serverSocket); serverSocketFactory.initSocket(socket); // Hand this socket off to an appropriate processor if (!processSocket(socket)) { // Close socket right away try { socket.close(); } catch (IOException e) { // Ignore } } }catch ( IOException x ) { if ( running ) log.error(sm.getString("endpoint.accept.fail"), x); } catch (Throwable t) { log.error(sm.getString("endpoint.accept.fail"), t); } // The processor will recycle itself when it finishes } }