Tomcat directory Structure
Base directory
Bin directory
The conf directory
Analysis of Tomcat system architecture and principle
B/S (Browser/server mode) Browsers are client-side (sending HTTP requests) — > server-side
Request access process
Data depends on THE TCP/IP protocol, so the transmitted data contains the TCP request header and TCP request body.
The TCP request body is an HTTP packet, including the HTTP request header and HTTP request body.
Overall Architecture of the Tomcat system
Tomcat Request Process
Tomcat is an Http server (can receive and process Http requests, so Tomcat is an Http server)
Note that Tomcat implements the Servlet container as required by the Servlet specification and also functions as an HTTP server.
Tomcat has two important identities
1) HTTP server
2) Tomcat is a Servlet container
Tomcat Servlet container processing process
When a user requests a URL resource
1) The HTTP server encapsulates the request information in ServletRequest objects
2) Go further and call a specific Servlet in the Servlet container
3) In 2), the Servlet container gets the request and finds the corresponding Servlet according to the mapping between URL and Servlet
4) If the Servlet has not been loaded, create the Servlet with reflection and call the init method of the Servlet to complete initialization
5) The service method of this concrete Servlet is then called to process the request, and the result of the request processing is encapsulated with a ServletResponse object
6) Return the ServletResponse object to the HTTP server, which sends the response to the client
Overall Architecture of the Tomcat system
Tomcat designs two core components, Connector and Container, to fulfill the two core functions of Tomcat.
Connector, responsible for external communication: processing Socket connection, responsible for network byte stream and Request and Response object conversion;
Container, responsible for internal processing: loading and managing servlets, and handling Request requests specifically;
Connector component Coyote
(1) Coyote encapsulates the underlying network communication (Socket request and response processing)
(2) Coyote completely decouples Catalina containers (container components) from specific request protocols and IO operations (bio/ NIO models, etc.)
(3) Coyote converts the Socket input into a Request object, which is further encapsulated and sent to Catalina container for processing. After processing the Request, Catalina writes the result into the output stream through the Response object provided by Coyote
(4) Coyote is responsible for specific protocols (application layer) and IO (transport layer)
Tomcat supports a variety of application layer protocols and I/O models, as follows:
Before 8.0, Tomcat’s default I/O mode was BIO (synchronous blocking), and since then NIO. NIO, NIO2 and APR are superior to BIO in performance. Even Apache HTTP Server performance can be achieved with APR (which requires component installation).
Internal components and processes of Coyote
component | Function description |
---|---|
EndPoint | The EndPoint is a CoyoteCommunication endpoints, that is, the communication listening interface, the Socket receiving and sending processor, is the abstraction of the transport layer, so the EndPoint is used to implement the TCP/IP protocol |
Processor | Processor is a CoyoteProtocol processingInterface. If the EndPoint is used to implement TCP/IP negotiation, the Processor is used to implement THE HTTP protocol. The Processor receives the Socket from the EndPoint, reads the byte stream and parses it into Tomcat Request and Response objects. Through Adapter, the Processor is an abstraction of the application-layer protocol |
ProtocolHandler | Coyote protocol interface, which implements protocol-specific processing capabilities through the Endpoint and Processor. Tomcat provides six implementation classes by protocol and I/O: AjpNioProtocol AjpAprProtocol AjpNio2Protocol Http11NioProtocol Http11Nio2Protocol Http11AprProtocol |
Adapter | Due to theAgreement is differentTomcat defines its own Request class to encapsulate the Request information. The ProtocolHandler interface is responsible for resolving requests and generating Tomcat Request classes. But the Request object is not a standard ServletRequest, and the container cannot be called with the Tomcat Request as an argument. The Tomcat designer’s solution was to introduce CoyoteAdapter, a classic use of the adapter pattern. The connector calls the Sevice method of CoyoteAdapter, passing in the Tomcat Request object, which CoyoteAdapter takes care ofConvert the Tomcat Request into a ServletRequest, and then call the container |
The Servlet container Catalina
At the heart of Tomcat is Catalina
Tomcat is a Web container made up of a series of configurable (conf/server.xml) components, and Catalina is Tomcat’s servlet container.
Tomcat, on the other hand, is essentially a Servlet container, because Catalina is the heart of Tomcat, and all the other modules support Catalina. For example, Coyote module provides link communication, Jasper module provides JSP engine, Naming provides JNDI service, and Juli provides logging service.
Servlet container structure of Catalina
When Tomcat starts, it initializes the instance. The Catalina instance creates other instances by loading server. XML, creating and managing a server, which creates and manages multiple services. Each service can have multiple connectors and one Container.
Catalina parses the Tomcat configuration file (server.xml) to create and manage the server component, which represents the entire Catalina Servlet container and other components. Responsible for assembling and starting Servlaet engine,Tomcat connector. The Lifecycle interface is implemented by the Server to provide an elegant way to start and shut down the entire system. Services are components within a Server that contain multiple services. It binds several Connector components to a Container Container, which handles the user’s servlet requests and returns objects to the Web user’s module
Container component structure
There are several specific components under the Container component: Engine, Host, Context, and Wrapper. These four components (containers) are parent-child relationships.
Engine represents the Servlet Engine of Catalina. It is used to manage multiple virtual sites. A Service can have at most one Engine, but an Engine can contain multiple hosts. Tomcat can be configured with multiple virtual host addresses, and a single virtual host can contain multiple contexts. Context represents a Web application, and a Web application can contain multiple wrappers. The Wrapper is the lowest layer of the container and cannot contain child containers. The configuration of the above component is shown in conf/server.xml
Details on core configuration of the Tomcat server
- Tomcat as a server configuration, mainly the configuration of server.xml file;
- Server.xml contains the configuration of the Servlet container, that is, Catalina;
- The Xml file presentation focuses on the use of tags
Main labels:
<! Create a Server instance with the Listener, GlobalNamingResources, Service -->
<Server>
<! -- Define listener -->
<Listener/>
<! Define global JNDI resources for the server
<GlobalNamingResources/>
<! A Server tag can have multiple instances of a Service.
<Service/>
</Server>
Copy the code
Description of the Server label
<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 -->
<! -- Load (server start) and destroy (server stop) APRs. If the APR library is not found, it will print a log, and it does not affect Tomcat startup.
<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
<! -- Prevent memory leaks due to use of particular java/javax APIs-->
<! -- Avoid JRE memory leaks -->
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
<! Load (server started) and destroy (server stopped) global naming service -->
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
<! Rebuild threads in the Executor pool when Context stops to avoid ThreadLocal related memory leaks
<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>
<Service name="Catalina">.</Service>
</Server>
Copy the code
The Service tag
<! - the label is used to create the Service instance, use the default org. Apache. Catalina. Core. StandardService. By default, Tomcat only specifies the name of the Service and the value is "Catalina". The Service subtags are Listener, Executor, Connector, and Engine. A Listener is used to add a lifecycle Listener to a Service, an Executor is used to configure a Service shared thread pool, and a Connector is used to configure a Service containing a linker. Engine is used to configure the Servlet container Engine corresponding to the linker in the Service.
<Service name="Catalina">.</Service>
Copy the code
Executor label
<! By default, Service does not add shared thread pool configuration. If we want to add a thread pool, we can add the following configuration under <Service> : name: the thread pool name used to specify namePrefix in Connector: NamePrefix +threadNumber maxThreads: the maximum number of threads in the pool minSpareThreads: MaxIdleTime: specifies the number of threads that are active, that is, the number of core pool threads. These threads will not be destroyed, but will always exist. MaxIdleTime: Specifies the number of idle threads that will be destroyed after this time. The maximum number of threads queued before being executed defaults to the maximum value of Int, which is generalized infinite. PrestartminSpareThreads: Whether to start a portion of minSpareThreads when starting the thread pool. ThreadPriority: specifies the priority of a thread in the thread pool. The default value is 5 and the value ranges from 1 to 10. ClassName: Thread pool implementation class, is not specified, the default implementation class is org. Apache. Catalina. Core. StandardThreadExecutor. If you want to use a custom thread pool need to implement the org. Apache. Catalina. The Executor interface - >
<Executor name="commonThreadPool"
namePrefix="thread-exec-"
maxThreads="200"
minSpareThreads="100"
maxIdleTime="60000"
maxQueueSize="Integer.MAX_VALUE"
prestartminSpareThreads="false"
threadPriority="5"
className="org.apache.catalina.core.StandardThreadExecutor"/>
Copy the code
The Connector label
<! -- port: Connector is used to create a server Socket and listen for a connection request from a client. If this property is set to 0, Tomcat will randomly select an available port number for the current Connector using Protocol: the access protocol supported by the current Connector. The default is HTTP/1.1, with automatic switching between a JAVA NIO based linker and a local APR based linker (depending on whether the local library contains Tomcat) connectionTimeOut: Connector Wait timeout time after receiving a link, in milliseconds. -1 indicates no timeout. RedirectPort: The Connector does not support SSL requests. When receiving a request that meets the Security-constraint constraint and requires SSL transmission, Catalina automatically redirects the request to the specified port. Executor: Specifies the name of the shared thread pool. You can also configure an internal thread pool using properties such as maxThreads and minSpareThreads. URIEncoding: Character encoding used to specify the encoding URI. The default encoding is UTF-8 for Tomcat8.x and ISO-8859-1 for Tomcat7.x.
<! - org. Apache. Coyote. Http11. Http11NioProtocol, non-blocking type Java NIO linker -- -- >
<Connector port="8080" protocol="HTTP / 1.1" connectionTimeout="20000"
redirectPort="8443" />
<Connector port="8009" protocol="AJP / 1.3" redirectPort="8443" />
Copy the code
Use a shared thread pool
<Connector port="8080"
protocol="HTTP / 1.1"
executor="commonThreadPool"
maxThreads="1000"
minSpareThreads="100"
acceptCount="1000"
maxConnections="1000"
connectionTimeout="20000"
compression="on"
compressionMinSize="2048"
disableUploadTimeout="true"
redirectPort="8443"
URIEncoding="UTF-8" />
Copy the code
- Executor specifies a shared thread pool
- MaxThreads is consistent with maxConnections
- Compression enables zip compression, on enables zip compression (rarely configured)
Engine label
Engine stands for Servlet Engine
<! -- name: specifies the name of the Engine. Default is Catalina defaultHost: specifies the name of the default virtual Host. If a client requests an invalid Host, the Host will be processed by the default virtual Host.
<Engine name="Catalina" defaultHost="localhost">.</Engine>
Copy the code
The Host label
<! --Host tag is used to configure a virtual Host -->
<Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true">.</Host>
Copy the code
The Context label
<Host name="www.abc.com" appBase="webapps" unpackWARs="true" autoDeploy="true">
<! DocBase: the deployment path of the Web application directory or War package. It can be an absolute path or a relative path to Host appBase. Path: indicates the Context path of the Web application. If we Host name localhost, the access path to the root of the web application: http://localhost:8080/web_demo. -->
<Context docBase="/Users/yingdian/web_demo" path="/web3"></Context>
<Valve className="org.apache.catalina.valves.AccessLogValve"
directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
</Host>
Copy the code
Note: Valve is not value; this label translates as Valve