Tomcat internal structure and request process

Source: Internet
Author: User

1. What is Tomcat

Tomcat is a jsp/servlet container. As a servlet container, there are three modes of operation: a standalone servlet container, a servlet container within the process, and a servlet container out-of-process.

2.TOMCAT Organizational Structure

Tomcat is a component-based server, and its constituent components are configurable, the outermost of which is the Catalina servlet container, and the other components are configured in this top-level container according to some format requirements.
The various components of Tomcat are configured in the/conf/server.xml file in the Tomcat installation directory.

Look at the architecture of Tomcat by the SERVER.XML structure:

<Server>                                                //top-level class elements, which can include multiple Service   
    <Service>                                           //top-level class elements, can contain one engine, multiple connecter
        < The connector>                                     ///connector class element, representing the communication interface
                <Engine>                                //Container class element, handles the customer request for a specific service component, including multiple Host
                        
The actual source code is as follows:
<?xml version= ' 1.0 ' encoding= ' utf-8 '?> <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"/> <!--Initialize Jasper prior to WebApps is loaded. Documentation At/docs/jasper-howto.html--<listener classname= "Org.apache.catalina.core.JasperListener"/ > <!--Prevent memory leaks due to use of particular Java/javax apis--> <listener classname= "org.apache.ca Talina.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--&
  Gt <GlobalNamingResources> <!--Editable User database that can also is used by Userdatabaserealm to AU Thenticate users--<resource name= "Userdatabase" auth= "Container" type= "Org.apache.catalina. Userdatabase "description=" User database, can be updated and saved "factory=" org.apache.ca Talina.users.MemoryUserDatabaseFactory "pathname=" Conf/tomcat-users.xml "/> </globalnamingresources&
  Gt <!--a "service" is a collection of one or more "connectors" that share a "Container" note:a "service"
       Is isn't itself a "Container", so if you are not define subcomponents such as "valves" at the 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-e xec-"maxthreads=" minsparethreads= "4"/>-<!--A "Connector" represents an endpoint by WHI CH Requests is received and responses are returned. Documentation At:java HTTP Connector:/docs/config/http.html (Blocking & non-blocking) Java AJP C Onnector:/docs/config/ajp.html APR (HTTP/AJP) Connector:/docs/apr.html Define a Non-ssl http/1.1 conne
               ctor on port 8080-<connector port= "8080" protocol= "http/1.1" connectiontimeout= "20000" redirectport= "8443"/> <!--A "Connector" using the shared thread pool--> <!--<co Nnector executor= "Tomcatthreadpool" port= "8080" protocol= "http/1.1" connectiontimeout= "20000 "redirectport=" 8443 "/>-<!--Define a SSL http/1.1 Connector on port 8443 This Connector uses the BIO implementation that requires the JSSE style Confi Guration. When using the apr/native implementation, the OpenSSL style configuration is required as described in the Apr/nat Ive documentation-<!--<connector port= "8443" protocol= "Org.apache.coyote.http11.Http11Proto Col "maxthreads=" sslenabled= "true" scheme= "https" secure= "true" Clientauth= "false" SslP Rotocol= "TLS"/>-<!--Define an AJP 1.3 Connector on port 8009-<connector port= "8009" p Rotocol= "ajp/1.3" redirectport= "8443"/> <!--an Engine represents the entry point (within Catalina) that Proces  SES 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 -<!--should set Jvmroute to support load-balancing via AJP ie: <engine name= "Catalina" Defaulth  ost= "localhost" jvmroute= "jvm1" > <engine name= "Catalina" defaulthost= "localhost" > <!--for Clustering documentation at:/docs/cluster-howto.html, * * */docs/c onfig/cluster.html (reference documentation)-<!--<cluster classname= "org.apache.catalina.ha.tcp.
           Simpletcpcluster "/>-<!--use the Lockoutrealm-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 is performed against this userdatabase is immediately available for use by the  Realm. -<rEalm classname= "Org.apache.catalina.realm.UserDatabaseRealm" resourcename= "Userdatabase"/> </re alm> The architecture of Tomcat can be derived from the above:


The image above shows that the heart of TOMCA is two components: Connecter and container. A container can select multiple connecter, multiple connector and a container form a service. The service can provide services externally, and the server server controls the entire Tomcat lifecycle.

The lifeline of the component "Lifecycle"

Service and Server manage the life cycle of the components under it.
The lifecycle of components in Tomcat is controlled through the Lifecycle interface, which can be uniformly controlled by the components that own it, so that the component inherits the interface and implements it, so that one layer at a time can control the life cycle of all components in Tomcat. This highest component is server, and the control server is startup, which means you start and shut Tomcat.

3.Connecter and Container

⑴connecter Components

A connecter will listen for a client request on a specified port, receive a TCP connection request from the browser, create a solicit and Response object to exchange data for and from the requester, and then generate a thread to process the request and generate the requested and The Response object is passed to the processing engine (part of the container), receives a response from the engine, and returns the customer.
There are two classic connector in Tomcat, one that listens directly to HTTP requests from browser, and another from other webserver requests. Cotote http/1.1 Connector listens for HTTP requests from customer browser at port 8080, Coyote JK2 Connector listens for servlet/jsp requests from other Web servers at Port 8009.
Connector the most important function is to receive the connection request and then assign the line Chengyang Container to handle this request, so this is necessarily multi-threaded, multi-threaded processing is the core of Connector design.
⑵container Components

The architecture of the container is as follows:


Container is the container's parent interface, the container is designed with a typical responsibility chain design pattern, it is composed of four self-container components, namely engine, Host, Context, Wrapper. These four components are responsible for the relationship, and there is a containment relationship. Typically a servlet class corresponds to a wrapper, if more than one servlet defines multiple wrapper, if there is more than one wrapper define a higher container, such as the context.
Context can also be defined in the parent container host, host is not required, but to run the war program, you have to host, because the war must have the Web. xml file, the parsing of this file requires host, if you want to have more than one host will define a top Container Engine. The engine does not have a parent container, and an engine represents a complete Servlet engine.

①engine container
Engine container is relatively simple, it only defines a few basic correlation relations
②host container
Host is a child of the engine, and a host in the engine represents a virtual host, which is the role of running multiple applications, which installs and expands these applications and identifies the application so that it can differentiate between them. Its sub-container is usually the context, which in addition to the associated sub-container, there is a storage of the host should have information.
③context container
The context represents the context of the servlet, which has a basic environment for the servlet to run, theoretically running the servlet as long as there is a context. Simple Tomcat can have no Engine and Host. The most important function of the context is to manage the servlet instances in it, the servlet instances in the context are Wrapper, and the other is how the context can find the right servlet to execute it. TOMCAT5 was previously managed by a Mapper class, and after TOMCAT5 this function was moved to request, it was found in the previous time series that the get sub-containers were allocated through request.
④wrapper container
Wrapper represents a servlet that manages the loading, initialization, execution, and resource recycling of a servlet, including Servlets. Wrapper is the lowest-level container, it has no sub-container, so the addChild that call it will get an error.
The Wrapper implementation class is Standardwrapper,standardwrapper also implements a servletconfig that has a servlet initialization information, which shows that Standardwrapper will directly and servlet To deal with all kinds of information.

Other components in 4.Tomcat

Tomcat also has other important components such as security components, logger log components, session, Mbeans, naming and other components. Together, these components provide the necessary services for Connector and Container.

the process of 5.Tomcat Server processing an HTTP request


⑴ the user clicks on the content of the webpage, the request is sent to the native port 8080, where the listening Coyote http/1.1 connector obtained.
⑵connector the request to the engine of the service it is working on, and waits for the engine to respond.
⑶engine gets the request localhost/test/index.jsp, matching all the virtual host hosts.
⑷engine matches a host named localhost (even if it does not match the request to the host, because the host is defined as the engine's default host), host with the name localhost gets the request/test/ index.jsp, matching all of the context it owns. The host matches to the context where the path is/test (if the match is not matched, the request is given to the context where the path name "" is processed).
The context of the ⑸path= "/test" obtains the request/index.jsp, looking for the corresponding servlet in its mapping table. The context matches to a servlet with a URL pattern of *.jsp, corresponding to the Jspservlet class.
⑹ constructs HttpServletRequest objects and HttpServletResponse objects, calling Jspservlet doget () or Dopost () as parameters. Execute the business logic, data storage and other programs.
⑺context returns the HttpServletResponse object after execution to host.
⑻host the HttpServletResponse object back to the engine.
⑼engine returns the HttpServletResponse object to connector.
⑽connector returns the HttpServletResponse object to the customer browser.

6.Tomcat Tuning

The maximum number of threads that can be maxthreads-tomcat thread pool
maxconnections-tomcat requests (connections) that can be processed concurrently
Acceptcount-tomcat maintain the largest number
of columns Minsparethreads-tomcat the thread pool size initialized or the Tomcat thread pool will have at least as many threads.

MaxThreads refers to the number of threads that the tomcat thread pool can play
MaxConnections is the number of concurrent connections that Tomcat can handle in a flash. For example maxthreads=1000,maxconnections=800, assuming a moment of concurrency of 1000, then eventually the number of Tomcat threads will be 800, that is, processing 800 requests at the same time, the remaining 200 into the queue "queued", If acceptcount=100, then 100 requests will be rejected.

Note: According to the foregoing, only the concurrency that moment Tomcat will be 800 threads processing requests, but after stability, a moment may be only a few threads in the runnable state, most of the thread is timed_waiting, if your application processing time fast enough. So the number of threads that really decide which Tomcat is the most likely to reach is maxconnections this parameter and the number of concurrent numbers, and when the number of concurrent numbers exceeds this parameter the request is queued, and the speed of the response depends on your program performance.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.