zoukankan      html  css  js  c++  java
  • Tomcat内部结构及请求原理(转)

    Tomcat

    Tomcat是一个JSP/Servlet容器。其作为Servlet容器,有三种工作模式:独立的Servlet容器、进程内的Servlet容器和进程外的Servlet容器。

    Tomcat的组织结构

    Tomcat是一个基于组件的服务器,它的构成组件都是可配置的,其中最外层的是Catalina servlet容器,其他组件按照一定的格式要求配置在这个顶层容器中。 
    Tomcat的各种组件都是在Tomcat安装目录下的/conf/server.xml文件中配置的。

    Tomcat目录

    tomcat
      |---bin:存放启动和关闭tomcat脚本

      |---conf:存放不同的配置文件(server.xml和web.xml);
      |---doc:存放Tomcat文档;
      |---lib/japser/common:存放Tomcat运行需要的库文件(JARS);
      |---logs:存放Tomcat执行时的LOG文件;
      |---src:存放Tomcat的源代码;
      |---webapps:Tomcat的主要Web发布目录(包括应用程序示例);
      |---work:存放jsp编译后产生的class文件;

    TomCat配置文件

    • server.xml: Tomcat的主配置文件,包含Service, Connector, Engine, Realm, Valve, Hosts主组件的相关配置信息;
    • web.xml:遵循Servlet规范标准的配置文件,用于配置servlet,并为所有的Web应用程序提供包括MIME映射等默认配置信息;
    • tomcat-user.xml:Realm认证时用到的相关角色、用户和密码等信息;Tomcat自带的manager默认情况下会用到此文件;在Tomcat中添加/删除用户,为用户  指定角色等将通过编辑此文件实现;
    • catalina.policy:Java相关的安全策略配置文件,在系统资源级别上提供访问控制的能力;
    • catalina.properties:Tomcat内部package的定义及访问相关控制,也包括对通过类装载器装载的内容的控制;Tomcat在启动时会事先读取此文件的相关设置;
    • logging.properties: Tomcat6通过自己内部实现的JAVA日志记录器来记录操作相关的日志,此文件即为日志记录器相关的配置信息,可以用来定义日志记录的组  件级别以及日志文件的存在位置等;
    • context.xml:所有host的默认配置信息;

    Tomcat架构及常用的组件:

    1、Server组件

    如上面示例文件中定义的:

    <Server port=”8005” shutdown=”SHUTDOWN”>

    这会让Tomcat6启动一个server实例(即一个JVM),它监听在8005端口以接收shutdown命令,使用 telnet 连接8005 端口可以直接执行 SHUTDOWN 命令来关闭 Tomcat。各Server的定义不能使用同一个端口,这意味着如果在同一个物理机上启动了多个Server实例,必须配置它们使用不同的端口。这个端口的定义用于为管理员提供一个关闭此实例的便捷途径,因此,管理员可以直接telnet至此端口使用SHUTDOWN命令关闭此实例。不过,基于安全角度的考虑,这通常不允许远程进行。

    Server的相关属性:

    className: 用于实现此Server容器的完全限定类的名称,默认为org.apache.catalina.core.StandardServer;

    port: 接收shutdown指令的端口,默认仅允许通过本机访问,默认为8005;

    shutdown:发往此Server用于实现关闭tomcat实例的命令字符串,默认为SHUTDOWN;

    2、Service组件:

    Service主要用于关联一个引擎和与此引擎相关的连接器,每个连接器通过一个特定的端口和协议接收入站请求交将其转发至关联的引擎进行处理。困此,Service要包含一个引擎、一个或多个连接器。

    如上面示例中的定义:

    <Service name=”Catalina”>

    这定义了一个名为Catalina的Service,此名字也会在产生相关的日志信息时记录在日志文件当中。

    Service相关的属性:

    className: 用于实现service的类名,一般都是org.apache.catalina.core.StandardService。

    name:此服务的名称,默认为Catalina;

    3、Connector组件:

    进入Tomcat的请求可以根据Tomcat的工作模式分为如下两类:

    Tomcat作为应用程序服务器:请求来自于前端的web服务器,这可能是Apache, IIS, Nginx等;

    Tomcat作为独立服务器:请求来自于web浏览器;

    Tomcat应该考虑工作情形并为相应情形下的请求分别定义好需要的连接器才能正确接收来自于客户端的请求。一个引擎可以有一个或多个连接器,以适应多种请求方式。

    定义连接器可以使用多种属性,有些属性也只适用于某特定的连接器类型。一般说来,常见于server.xml中的连接器类型通常有4种:

    1) HTTP连接器 2) SSL连接器 3) AJP 1.3连接器 4) proxy连接器

    如上面示例server.xml中定义的HTTP连接器:

    <Connector port=”8080″ protocol=”HTTP/1.1″
    maxThreads=”150″ connectionTimeout=”20000″
    redirectPort=”8443″/>

    定义连接器时可以配置的属性非常多,但通常定义HTTP连接器时必须定义的属性只有“port“,定义AJP连接器时必须定义的属性只有”protocol”,因为默认的协议为HTTP。以下为常用属性的说明:

    下面是一个定义了多个属性的SSL连接器:

    <Connector port=”8443″
    maxThreads=”150″ minSpareThreads=”25″ maxSpareThreads=”75″
    enableLookups=”false” acceptCount=”100″ debug=”0″ scheme=”https” secure=”true”
    clientAuth=”false” sslProtocol=”TLS” />

    4、Engine组件:

    Engine是Servlet处理器的一个实例,即servlet引擎,默认为定义在server.xml中的Catalina。Engine需要defaultHost属性来为其定义一个接收所有发往非明确定义虚拟主机的请求的host组件。如前面示例中定义的:

    <Engine name=”Catalina” defaultHost=”localhost”>

    常用的属性定义:

    defaultHost:Tomcat支持基于FQDN的虚拟主机,这些虚拟主机可以通过在Engine容器中定义多个不同的Host组件来实现;但如果此引擎的连接器收到一个发往非非明确定义虚拟主机的请求时则需要将此请求发往一个默认的虚拟主机进行处理,因此,在Engine中定义的多个虚拟主机的主机名称中至少要有一个跟defaultHost定义的主机名称同名;

    name:Engine组件的名称,用于日志和错误信息记录时区别不同的引擎;

    Engine容器中可以包含Realm、Host、Listener和Valve子容器。

    5、Host组件:

    位于Engine容器中用于接收请求并进行相应处理的主机或虚拟主机,如前面示例中的定义:

    <Host name=”localhost” appBase=”webapps”
    unpackWARs=”true” autoDeploy=”true”
    xmlValidation=”false” xmlNamespaceAware=”false”>
    </Host>

    常用属性说明:

    虚拟主机定义示例:

    <Engine name=”Catalina” defaultHost=”localhost”>
    <Host name=”localhost” appBase=”webapps”>
    <Context path=”” docBase=”ROOT”/>
    <Context path=”/bbs” docBase=”/web/bss”  #path路径是定义在defaultHost背后的
    reloadable=”true” crossContext=”true”/>
    </Host>
    
    <Host name=”mail.magedu.com” appBase=”/web/mail”>
    <Context path=”” docBase=”ROOT”/>
    </Host>
    </Engine>

    主机别名定义:

    如果一个主机有两个或两个以上的主机名,额外的名称均可以以别名的形式进行定义,如下:

    <Host name=”www.ttlsa.com” appBase=”webapps” unpackWARs=”true”>
    <Alias>feiyu.com</Alias>
    </Host>

    6、Context组件:

    Context在某些意义上类似于apache中的路径别名,一个Context定义用于标识tomcat实例中的一个Web应用程序;如下面的定义:

    <!– Tomcat Root Context –>
    <Context path=”” docBase=”/web/webapps”/>
    
    <!– buzzin webapp –>
    <Context path=”/bbs”
    docBase=”/web/threads/bbs”
    reloadable=”true”>
    </Context>
    
    <!– chat server –>
    <Context path=”/chat” docBase=”/web/chat”/>
    
    <!– darian web –>
    <Context path=”/darian” docBase=”darian”/>

    在Tomcat6中,每一个context定义也可以使用一个单独的XML文件进行,其文件的目录为$CATALINA_HOME/conf//。可以用于Context中的XML元素有Loader,Manager,Realm,Resources和WatchedResource。

    常用的属性定义有:

    7、Realm组件:

    一个Realm表示一个安全上下文,它是一个授权访问某个给定Context的用户列表和某用户所允许切换的角色相关定义的列表。因此,Realm就像是一个用户和组相关的数据库。定义Realm时惟一必须要提供的属性是classname,它是Realm的多个不同实现,用于表示此Realm认证的用户及角色等认证信息的存放位置。

    8、Valve组件:

    Valve类似于过滤器,它可以工作于Engine和Host/Context之间、Host和Context之间以及Context和Web应用程序的某资源之间。一个容器内可以建立多个Valve,而且Valve定义的次序也决定了它们生效的次序。Tomcat6中实现了多种不同的Valve:

    下面是一个常见的使用UserDatabase的配置:

    <Realm className=”org.apache.catalina.realm.UserDatabaseRealm”
    resourceName=”UserDatabase”/>

    下面是一个使用JDBC方式获取用户认证信息的配置:

    <Realm className=”org.apache.catalina.realm.JDBCRealm” debug=”99″
    driverName=”org.gjt.mm.mysql.Driver”
    connectionURL=”jdbc:mysql://localhost/authority”
    connectionName=”test” connectionPassword=”test”
    userTable=”users” userNameCol=”user_name”
    userCredCol=”user_pass”
    userRoleTable=”user_roles” roleNameCol=”role_name” />

    8、Valve组件:

    Valve类似于过滤器,它可以工作于Engine和Host/Context之间、Host和Context之间以及Context和Web应用程序的某资源之间。一个容器内可以建立多个Valve,而且Valve定义的次序也决定了它们生效的次序。Tomcat6中实现了多种不同的Valve:

    RemoteHostValve和RemoteAddrValve可以分别用来实现基于主机名称和基于IP地址的访问控制,控制本身可以通过allow或deny来进行定义,这有点类似于Apache的访问控制功能;如下面的Valve则实现了仅允许本机访问/probe:

    <Context path=”/probe” docBase=”probe”>
    <Valve className=”org.apache.catalina.valves.RemoteAddrValve”
    allow=”127.0.0.1″/>
    </Context>

    由Server.xml的结构看Tomcat的体系结构

    <Server>                                                //顶层类元素,可以包括多个Service   
        <Service>                                           //顶层类元素,可包含一个Engine,多个Connecter
            <Connector>                                     //连接器类元素,代表通信接口
                    <Engine>                                //容器类元素,为特定的Service组件处理客户请求,要包含多个Host
                            <Host>                          //容器类元素,为特定的虚拟主机组件处理客户请求,可包含多个Context
                                    <Context>               //容器类元素,为特定的Web应用处理所有的客户请求
                                    </Context>
                            </Host>
                    </Engine>
            </Connector>
        </Service>
    </Server>

    server.xml源码如下

    <?xml version="1.0" encoding="UTF-8"?>
    <!--
      Licensed to the Apache Software Foundation (ASF) under one or more
      contributor license agreements.  See the NOTICE file distributed with
      this work for additional information regarding copyright ownership.
      The ASF licenses this file to You under the Apache License, Version 2.0
      (the "License"); you may not use this file except in compliance with
      the License.  You may obtain a copy of the License at
    
          http://www.apache.org/licenses/LICENSE-2.0
    
      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.
    -->
    <!-- Note:  A "Server" is not itself a "Container", so you may not
         define subcomponents such as "Valves" at this level.
         Documentation at /docs/config/server.html
     -->
    <Server port="8005" shutdown="SHUTDOWN">
      <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
      <!-- Security listener. Documentation at /docs/config/listeners.html
      <Listener className="org.apache.catalina.security.SecurityListener" />
      -->
      <!--APR library loader. Documentation at /docs/apr.html -->
      <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
      <!-- Prevent memory leaks due to use of particular java/javax APIs-->
      <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
      <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
      <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />
    
      <!-- Global JNDI resources
           Documentation at /docs/jndi-resources-howto.html
      -->
      <GlobalNamingResources>
        <!-- Editable user database that can also be used by
             UserDatabaseRealm to authenticate users
        -->
        <Resource name="UserDatabase" auth="Container"
                  type="org.apache.catalina.UserDatabase"
                  description="User database that can be updated and saved"
                  factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
                  pathname="conf/tomcat-users.xml" />
      </GlobalNamingResources>
    
      <!-- A "Service" is a collection of one or more "Connectors" that share
           a single "Container" Note:  A "Service" is not itself a "Container",
           so you may not define subcomponents such as "Valves" at this level.
           Documentation at /docs/config/service.html
       -->
      <Service name="Catalina">
    
        <!--The connectors can use a shared executor, you can define one or more named thread pools-->
        <!--
        <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
            maxThreads="150" minSpareThreads="4"/>
        -->
    
    
        <!-- A "Connector" represents an endpoint by which requests are received
             and responses are returned. Documentation at :
             Java HTTP Connector: /docs/config/http.html
             Java AJP  Connector: /docs/config/ajp.html
             APR (HTTP/AJP) Connector: /docs/apr.html
             Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
        -->
        <Connector port="8080" protocol="HTTP/1.1"
                   connectionTimeout="20000"
                   redirectPort="8443" />
        <!-- A "Connector" using the shared thread pool-->
        <!--
        <Connector executor="tomcatThreadPool"
                   port="8080" protocol="HTTP/1.1"
                   connectionTimeout="20000"
                   redirectPort="8443" />
        -->
        <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
             This connector uses the NIO implementation. The default
             SSLImplementation will depend on the presence of the APR/native
             library and the useOpenSSL attribute of the
             AprLifecycleListener.
             Either JSSE or OpenSSL style configuration may be used regardless of
             the SSLImplementation selected. JSSE style configuration is used below.
        -->
        <!--
        <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
                   maxThreads="150" SSLEnabled="true">
            <SSLHostConfig>
                <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
                             type="RSA" />
            </SSLHostConfig>
        </Connector>
        -->
        <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
             This connector uses the APR/native implementation which always uses
             OpenSSL for TLS.
             Either JSSE or OpenSSL style configuration may be used. OpenSSL style
             configuration is used below.
        -->
        <!--
        <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
                   maxThreads="150" SSLEnabled="true" >
            <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
            <SSLHostConfig>
                <Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
                             certificateFile="conf/localhost-rsa-cert.pem"
                             certificateChainFile="conf/localhost-rsa-chain.pem"
                             type="RSA" />
            </SSLHostConfig>
        </Connector>
        -->
    
        <!-- Define an AJP 1.3 Connector on port 8009 -->
        <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
    
    
        <!-- An Engine represents the entry point (within Catalina) that processes
             every request.  The Engine implementation for Tomcat stand alone
             analyzes the HTTP headers included with the request, and passes them
             on to the appropriate Host (virtual host).
             Documentation at /docs/config/engine.html -->
    
        <!-- You should set jvmRoute to support load-balancing via AJP ie :
        <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
        -->
        <Engine name="Catalina" defaultHost="localhost">
    
          <!--For clustering, please take a look at documentation at:
              /docs/cluster-howto.html  (simple how to)
              /docs/config/cluster.html (reference documentation) -->
          <!--
          <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
          -->
    
          <!-- Use the LockOutRealm to prevent attempts to guess user passwords
               via a brute-force attack -->
          <Realm className="org.apache.catalina.realm.LockOutRealm">
            <!-- This Realm uses the UserDatabase configured in the global JNDI
                 resources under the key "UserDatabase".  Any edits
                 that are performed against this UserDatabase are immediately
                 available for use by the Realm.  -->
            <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
                   resourceName="UserDatabase"/>
          </Realm>
    
          <Host name="localhost"  appBase="webapps"
                unpackWARs="true" autoDeploy="true">
    
            <!-- SingleSignOn valve, share authentication between web applications
                 Documentation at: /docs/config/valve.html -->
            <!--
            <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
            -->
    
            <!-- Access log processes all example.
                 Documentation at: /docs/config/valve.html
                 Note: The pattern used is equivalent to using pattern="common" -->
            <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
                   prefix="localhost_access_log" suffix=".txt"
                   pattern="%h %l %u %t &quot;%r&quot; %s %b" />
    
          </Host>
        </Engine>
      </Service>
    </Server>
    View Code

    由上可得出Tomcat的体系结构: 
     
                 图一:Tomcat的体系结构

    由上图可看出Tomca的心脏是两个组件:Connecter和Container。一个Container可以选择多个Connecter,多个Connector和一个Container就形成了一个Service。Service可以对外提供服务,而Server服务器控制整个Tomcat的生命周期。

      • 组件的生命线“Lifecycle”

        Service 和 Server 管理它下面组件的生命周期。 
        Tomcat 中组件的生命周期是通过 Lifecycle 接口来控制的,组件只要继承这个接口并实现其中的方法就可以统一被拥有它的组件控制了,这样一层一层的直到一个最高级的组件就可以控制 Tomcat 中所有组件的生命周期,这个最高的组件就是 Server,而控制 Server 的是 Startup,也就是您启动和关闭 Tomcat。

    Tomca的两大组件:Connecter和Container

    Connecter组件

    一个Connecter将在某个指定的端口上侦听客户请求,接收浏览器的发过来的 tcp 连接请求,创建一个 Request 和 Response 对象分别用于和请求端交换数据,然后会产生一个线程来处理这个请求并把产生的 Request 和 Response 对象传给处理Engine(Container中的一部分),从Engine出获得响应并返回客户。 
    Tomcat中有两个经典的Connector,一个直接侦听来自Browser的HTTP请求,另外一个来自其他的WebServer请求。Cotote HTTP/1.1 Connector在端口8080处侦听来自客户Browser的HTTP请求,Coyote JK2 Connector在端口8009处侦听其他Web Server的Servlet/JSP请求。 
    Connector 最重要的功能就是接收连接请求然后分配线程让 Container 来处理这个请求,所以这必然是多线程的,多线程的处理是 Connector 设计的核心。

    Container组件

    Container的体系结构如下: 
     
            图二:Container的体系结构 
    Container是容器的父接口,该容器的设计用的是典型的责任链的设计模式,它由四个自容器组件构成,分别是Engine、Host、Context、Wrapper。这四个组件是负责关系,存在包含关系。通常一个Servlet class对应一个Wrapper,如果有多个Servlet定义多个Wrapper,如果有多个Wrapper就要定义一个更高的Container,如Context。 
    Context 还可以定义在父容器 Host 中,Host 不是必须的,但是要运行 war 程序,就必须要 Host,因为 war 中必有 web.xml 文件,这个文件的解析就需要 Host 了,如果要有多个 Host 就要定义一个 top 容器 Engine 了。而 Engine 没有父容器了,一个 Engine 代表一个完整的 Servlet 引擎。

      • Engine 容器 
        Engine 容器比较简单,它只定义了一些基本的关联关系
      • Host 容器 
        Host 是 Engine 的字容器,一个 Host 在 Engine 中代表一个虚拟主机,这个虚拟主机的作用就是运行多个应用,它负责安装和展开这些应用,并且标识这个应用以便能够区分它们。它的子容器通常是 Context,它除了关联子容器外,还有就是保存一个主机应该有的信息。
      • Context 容器 
        Context 代表 Servlet 的 Context,它具备了 Servlet 运行的基本环境,理论上只要有 Context 就能运行 Servlet 了。简单的 Tomcat 可以没有 Engine 和 Host。Context 最重要的功能就是管理它里面的 Servlet 实例,Servlet 实例在 Context 中是以 Wrapper 出现的,还有一点就是 Context 如何才能找到正确的 Servlet 来执行它呢? Tomcat5 以前是通过一个 Mapper 类来管理的,Tomcat5 以后这个功能被移到了 request 中,在前面的时序图中就可以发现获取子容器都是通过 request 来分配的。
      • Wrapper 容器 
        Wrapper 代表一个 Servlet,它负责管理一个 Servlet,包括的 Servlet 的装载、初始化、执行以及资源回收。Wrapper 是最底层的容器,它没有子容器了,所以调用它的 addChild 将会报错。 
        Wrapper 的实现类是 StandardWrapper,StandardWrapper 还实现了拥有一个 Servlet 初始化信息的 ServletConfig,由此看出 StandardWrapper 将直接和 Servlet 的各种信息打交道。

    Tomcat 中其它组件

    Tomcat 还有其它重要的组件,如安全组件 security、logger 日志组件、session、mbeans、naming 等其它组件。这些组件共同为 Connector 和 Container 提供必要的服务。

    Tomcat Server处理一个HTTP请求的过程

     
                  图三:Tomcat Server处理一个HTTP请求的过程

    Tomcat Server处理一个HTTP请求的过程

    1、用户点击网页内容,请求被发送到本机端口8080,被在那里监听的Coyote HTTP/1.1 Connector获得。 
    2、Connector把该请求交给它所在的Service的Engine来处理,并等待Engine的回应。 
    3、Engine获得请求localhost/test/index.jsp,匹配所有的虚拟主机Host。 
    4、Engine匹配到名为localhost的Host(即使匹配不到也把请求交给该Host处理,因为该Host被定义为该Engine的默认主机),名为localhost的Host获得请求/test/index.jsp,匹配它所拥有的所有的Context。Host匹配到路径为/test的Context(如果匹配不到就把该请求交给路径名为“ ”的Context去处理)。 
    5、path=“/test”的Context获得请求/index.jsp,在它的mapping table中寻找出对应的Servlet。Context匹配到URL PATTERN为*.jsp的Servlet,对应于JspServlet类。 
    6、构造HttpServletRequest对象和HttpServletResponse对象,作为参数调用JspServlet的doGet()或doPost().执行业务逻辑、数据存储等程序。 
    7、Context把执行完之后的HttpServletResponse对象返回给Host。 
    8、Host把HttpServletResponse对象返回给Engine。 
    9、Engine把HttpServletResponse对象返回Connector。 
    10、Connector把HttpServletResponse对象返回给客户Browser。

    文章引用自:http://www.cnblogs.com/hggen/p/6264475.html

                     http://www.cnblogs.com/zhouyuqin/p/5143121.html

  • 相关阅读:
    Docker没有vi命令的解决方案
    docker-compose
    liunx 删除文件
    OPB_发票信息表(每笔结算生成一条数据) opb_invoiceinfo
    OPB_发票明细表(每一类药品生成一条数据) opb_invoicedetail
    工程启动类
    MySQL数据库启动,关闭,重启:
    linux压缩和解压缩命令
    降序限位排名
    PHP环境的塔建 防坑指南
  • 原文地址:https://www.cnblogs.com/lingyejun/p/7202821.html
Copyright © 2011-2022 走看看