Tomcat6.0连接器源码分析

简介:

首先看BIO模式。

Server.conf配置连接器如下:
<Connector port="8081" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
protocol设定为"HTTP/1.1",这里指org.apache.coyote.http11.Http11Protocol,
相应的转换代码在Connector类里:
 
 
  1. public void setProtocol(String protocol) {  
  2.         if (AprLifecycleListener.isAprAvailable()) {  
  3.             if ("HTTP/1.1".equals(protocol)) {  
  4.                 setProtocolHandlerClassName  
  5.                     ("org.apache.coyote.http11.Http11AprProtocol");  
  6.             } else if ("AJP/1.3".equals(protocol)) {  
  7.                 setProtocolHandlerClassName  
  8.                     ("org.apache.coyote.ajp.AjpAprProtocol");  
  9.             } else if (protocol != null) {  
  10.                 setProtocolHandlerClassName(protocol);  
  11.             } else {  
  12.                 setProtocolHandlerClassName  
  13.                     ("org.apache.coyote.http11.Http11AprProtocol");  
  14.             }  
  15.         } else {  
  16.             if ("HTTP/1.1".equals(protocol)) {  
  17.                 setProtocolHandlerClassName  
  18.                     ("org.apache.coyote.http11.Http11Protocol");  
  19.             } else if ("AJP/1.3".equals(protocol)) {  
  20.                 setProtocolHandlerClassName  
  21.                     ("org.apache.jk.server.JkCoyoteHandler");  
  22.             } else if (protocol != null) {  
  23.                 setProtocolHandlerClassName(protocol);  
  24.             }  
  25.         }  
我们这里没有apr 也没有ajp.所以ProtocolHandlerClassName就是org.apache.coyote.http11.Http11Protocol,Http11Protocol在init里,会初始化JioEndpoint。
以后的工作主要由JioEndpoint来处理请求连接,来看看JioEndpoint的init方法:
 
  
 
  1. public void init()  
  2.        throws Exception {  
  3.  
  4.        if (initialized)  
  5.            return;  
  6.          
  7.        // Initialize thread count defaults for acceptor  
  8.        if (acceptorThreadCount == 0) {  
  9.            acceptorThreadCount = 1;  
  10.        }  
  11.        if (serverSocketFactory == null) {  
  12.            serverSocketFactory = ServerSocketFactory.getDefault();  
  13.        }  
  14.        if (serverSocket == null) {  
  15.            try {  
  16.                if (address == null) {  
  17.                    serverSocket = serverSocketFactory.createSocket(port, backlog);  
  18.                } else {  
  19.                    serverSocket = serverSocketFactory.createSocket(port, backlog, address);  
  20.                }  
  21.            } catch (BindException orig) {  
  22.                String msg;  
  23.                if (address == null)  
  24.                    msg = orig.getMessage() + " <null>:" + port;  
  25.                else 
  26.                    msg = orig.getMessage() + " " +  
  27.                            address.toString() + ":" + port;  
  28.                BindException be = new BindException(msg);  
  29.                be.initCause(orig);  
  30.                throw be;  
  31.            }  
  32.        }  
  33.        //if( serverTimeout >= 0 )  
  34.        //    serverSocket.setSoTimeout( serverTimeout );  
  35.          
  36.        initialized = true;  
  37.          
主要目的就是创建ServerSocket. 有了服务端的listener.
 
Http11Protocol启动的时候,相应的启动JioEndpoint.
 
JioEndpoint 的start方法:
 
 
  1. public void start()  
  2.         throws Exception {  
  3.         // Initialize socket if not done before  
  4.         if (!initialized) {  
  5.            init();  
  6.         }  
  7.         if (!running) {  
  8.             running = true;  
  9.             paused = false;  
  10.    
  11.             // Create worker collection  
  12.             if (executor == null) {//目前executor都为空,非空的下一节会讨论  
  13.                 workers = new WorkerStack(maxThreads);//①.创建工作线程。  
  14.             }  
  15.    
  16.             // Start acceptor threads  
  17.             for (int i = 0; i < acceptorThreadCount; i++) {  
  18.                 Thread acceptorThread = new Thread(new Acceptor(), getName() + "-Acceptor-" + i);  
  19.                 acceptorThread.setPriority(threadPriority);  
  20.                 acceptorThread.setDaemon(daemon);  
  21.                 acceptorThread.start(); // 2.启动接收线程.  
  22.             }  
  23.         }  
  24.     }  
在①处,WorkerStack模拟一个栈,里面用数组存储工作线程(Tomcat这帮人就喜欢用数组)。用来处理请求过来的socket.
在2处,启动一个接收线程,接收请求连接。
 
Acceptor代码如下:
 
 
  1.  /**  
  2.      * Server socket acceptor thread.  
  3.      */ 
  4.     protected class Acceptor implements Runnable {  
  5.         /**  
  6.          * The background thread that listens for incoming TCP/IP connections and  
  7.          * hands them off to an appropriate processor.  
  8.          */ 
  9.         public void run() {  
  10.    
  11.             // Loop until we receive a shutdown command  
  12.             while (running) {  
  13.    
  14.                 // Loop if endpoint is paused  
  15.                 while (paused) {  
  16.                     try {  
  17.                         Thread.sleep(1000);  
  18.                     } catch (InterruptedException e) {  
  19.                         // Ignore  
  20.                     }  
  21.                 }  
  22.    
  23.                 // Accept the next incoming connection from the server socket  
  24.                 try {  
  25.                     Socket socket = serverSocketFactory.acceptSocket(serverSocket);  
  26.                     serverSocketFactory.initSocket(socket);  
  27.                     // Hand this socket off to an appropriate processor  
  28.                     if (!processSocket(socket)) {  
  29.                         // Close socket right away  
  30.                         try {  
  31.                             socket.close();  
  32.                         } catch (IOException e) {  
  33.                             // Ignore  
  34.                         }  
  35.                     }  
  36.                 }catch ( IOException x ) {  
  37.                     if ( running ) log.error(sm.getString("endpoint.accept.fail"), x);  
  38.                 } catch (Throwable t) {  
  39.                     log.error(sm.getString("endpoint.accept.fail"), t);  
  40.                 }  
  41.    
  42.                 // The processor will recycle itself when it finishes  
  43.    
  44.             }  
  45.    
  46.         }  
  47.     }  
  48. serverSocketFactory.acceptSocket用init方法里创建的severSocket accept一个连接Socket。然后processSocket(socket).  
  49. 下面看processSocke(socket)方法:  
  50.    
  51. protected boolean processSocket(Socket socket) {  
  52.         try {  
  53.             if (executor == null) { //目前executor都为空。  
  54.                 getWorkerThread().assign(socket);  
  55.             } else {  
  56.                 executor.execute(new SocketProcessor(socket));  
  57.             }  
  58.         } catch (Throwable t) {  
  59.             // This means we got an OOM or similar creating a thread, or that  
  60.             // the pool and its queue are full  
  61.             log.error(sm.getString("endpoint.process.fail"), t);  
  62.             return false;  
  63.         }  
  64.         return true;  
  65.     }  
getWorkerThread()方法是从刚才创建的工作线程栈WorkerStack中取得一个工作线程。
这段代码很简单,就不说了,有兴趣看一下Tomcat的源代码(Class:JioEndpoint).
 
我们看一下工作线程类Worker吗。
 
  1. protected class Worker implements Runnable {  
  2.    
  3.         protected Thread thread = null;  
  4.         protected boolean available = false;  
  5.         protected Socket socket = null;  
  6.    
  7.       /**  
  8.          * Process an incoming TCP/IP connection on the specified socket. Any  
  9.          * exception that occurs during processing must be logged and swallowed.  
  10.          * <b>NOTE</b>: This method is called from our Connector's thread. We  
  11.          * must assign it to our own thread so that multiple simultaneous  
  12.          * requests can be handled.  
  13.          *  
  14.          * @param socket TCP socket to process  
  15.          */ 
  16.         synchronized void assign(Socket socket) {  
  17.    
  18.             // Wait for the Processor to get the previous Socket  
  19.             while (available) {  
  20.                 try {  
  21.                     wait();  
  22.                 } catch (InterruptedException e) {  
  23.                 }  
  24.             }  
  25.             // Store the newly available Socket and notify our thread  
  26.             this.socket = socket;  
  27.             available = true;  
  28.             notifyAll();  
  29.    
  30.         }  
  31.    
  32.           
  33.         /**  
  34.          * Await a newly assigned Socket from our Connector, or <code>null</code>  
  35.          * if we are supposed to shut down.  
  36.          */ 
  37.        private synchronized Socket await() {  
  38.             // Wait for the Connector to provide a new Socket  
  39.             while (!available) {  
  40.                 try {  
  41.                     wait();  
  42.                 } catch (InterruptedException e) {  
  43.                 }  
  44.             }  
  45.    
  46.             // Notify the Connector that we have received this Socket  
  47.             Socket socket = this.socket;  
  48.             available = false;  
  49.             notifyAll();  
  50.    
  51.             return (socket);  
  52.    
  53.         }  
  54.         /**  
  55.          * The background thread that listens for incoming TCP/IP connections and  
  56.          * hands them off to an appropriate processor.  
  57.          */ 
  58.         public void run() {  
  59.    
  60.             // Process requests until we receive a shutdown signal  
  61.             while (running) {  
  62.    
  63.                 // Wait for the next socket to be assigned  
  64.                 Socket socket = await();  
  65.                 if (socket == null)  
  66.                     continue;  
  67.    
  68.                 // Process the request from this socket  
  69.                 if (!setSocketOptions(socket) || !handler.process(socket)) {  
  70.                     // Close socket  
  71.                     try {  
  72.                         socket.close();  
  73.                     } catch (IOException e) {  
  74.                     }  
  75.                 }  
  76.    
  77.                 // Finish up this request  
  78.                 socket = null;  
  79.                 recycleWorkerThread(this);  
  80.    
  81.             }  
  82.    
  83.         }  
  84.        /**  
  85.          * Start the background processing thread.  
  86.          */ 
  87.         public void start() {  
  88.             thread = new Thread(this);  
  89.             thread.setName(getName() + "-" + (++curThreads));  
  90.             thread.setDaemon(true);  
  91.             thread.start();  
  92.         }  
  93.     }  
首行看一下刚刚被调用的assign方法,Worker类通过available互斥。Available可理解为是否还有现成的Socket绑定在这个工作线程上,true表示有。Assign首先判断Available,如果有可用socket,即Available为true,则wait直到被唤醒。  This method is called from our Connector's thread.告诉我们该方法由连接器线程调用。那么工作线程自己呢。看run方法,调用了await,按照上面的理解,如果没有可用的socket,即Available为false,则wait直到被唤醒。如果为true,刚马上拿走这个socket.并把Available设为false.就可以有新的Socket放进来了。
 
但这里有点问题,从WorkerStack栈出取出的Worker或者新建的Worker,Available肯定都为false.那么assign方法的 while (available)循环就没有必要了。不清楚为什么作者这么写。
 
获得Socket之后交由handler去处理,这里的handler就
是Http11Protocol$Http11ConnectionHandler,处理流程,以会再讨论。

本文转自 anranran 51CTO博客,原文链接:http://blog.51cto.com/guojuanjun/538310

相关文章
|
6天前
|
XML 应用服务中间件 Apache
Tomcat AJP连接器配置secretRequired=“true“,但是属性secret确实空或者空字符串,这样的组合是无效的。
Tomcat AJP连接器配置secretRequired=“true“,但是属性secret确实空或者空字符串,这样的组合是无效的。
|
8月前
|
Arthas 弹性计算 安全
优雅上下线之如何安全的关闭Tomcat持久连接
优雅上下线之如何安全的关闭Tomcat持久连接
323 3
|
7月前
|
Web App开发 应用服务中间件
解决在访问tomcat时出现连接失败,Firefox 无法建立到 localhost:8080 服务器的连接的问题~
解决在访问tomcat时出现连接失败,Firefox 无法建立到 localhost:8080 服务器的连接的问题~
131 0
|
7月前
|
网络协议 应用服务中间件 Apache
100分布式电商项目 - Tomcat性能优化(禁用AJP连接器)
100分布式电商项目 - Tomcat性能优化(禁用AJP连接器)
36 0
|
7月前
|
应用服务中间件
IDEA 配置部署JavaWeb项目在阿里云服务器的tomcat上,成功连接服务器,但Artifact 没有成功部署
IDEA 配置部署JavaWeb项目在阿里云服务器的tomcat上,成功连接服务器,但Artifact 没有成功部署
447 0
|
8月前
|
Arthas 负载均衡 网络协议
Tomcat连接之KeepAlive逻辑分析
Tomcat连接之KeepAlive逻辑分析
217 1
|
弹性计算 Java 应用服务中间件
关于购买阿里云学生服务器以及win7安装Tomcat连接服务器的过程总结
关于购买阿里云学生服务器以及win7安装Tomcat连接服务器的过程总结
139 0
|
弹性计算 Oracle 安全
阿里云学生服务器(Windows)的配置以及安装Tomcat连接服务器的教程
阿里云学生服务器(Windows)的配置以及安装Tomcat连接服务器的教程
442 0
阿里云学生服务器(Windows)的配置以及安装Tomcat连接服务器的教程
|
应用服务中间件
tomcat升级版本为8.5.68后.启动报错: java.lang.IllegalArgumentException: AJP连接器配置secretRequired=“true”
ttomcat升级版本为8.5.68后.启动报错: java.lang.IllegalArgumentException: AJP连接器配置secretRequired=“true” 属性secret确实为空 1.tomcat启动报错内容如下
799 0
tomcat升级版本为8.5.68后.启动报错: java.lang.IllegalArgumentException: AJP连接器配置secretRequired=“true”
|
弹性计算 Oracle 安全
服务器配置:阿里云服务器(Windows)的配置以及安装Tomcat连接服务器的教程
服务器配置:阿里云服务器(Windows)的配置以及安装Tomcat连接服务器的教程
1745 0
服务器配置:阿里云服务器(Windows)的配置以及安装Tomcat连接服务器的教程