1, Introduction to Tomcat
Tomcat is a free and open source Web application server. It is a core open source project of the Apache Software Foundation and belongs to a lightweight application server.
1. What is Tomcat?
Tomcat: the platform for JAVA code running
Tomcat is a lightweight application server, which is widely used in small and medium-sized systems and when there are not many concurrent access users. It is the first choice for developing and debugging JSP programs.
Generally speaking, although Tomcat has the same function of processing HTML pages as Apache or Ningx, its ability to process static html is far less than Apache and Nginx.
Therefore, Tomcat usually runs separately on the back end as a servlet and JSP container.
Tomcat is a popular Web application service at present.
web Services: Web services, such as nginx. web Application services: that is, application services can be used web In the form of.
2. Tomcat core components
Generally speaking, after receiving the request, the Web server simply responds to static resources, such as HTML files, image files, etc., and cannot perform certain processing operations on the back end.
Tomcat is a sub project under Apache. It has all the functions of a Web server. It can not only listen and receive requests and respond to static resources, but also run JAVA code with specific specifications on the back end, and write the execution results back to the client in the form of HTML code.
tomcat There are three main containers: web Containers jsp Containers servlet Container. What is a container? A container encapsulates a set of resources/An individual of a functional set.
Tomcat is composed of a series of components, among which there are three core component containers:
- Web container: complete the functions of the web server and receive and respond to HTTP/HTTPS requests.
Description: ① receive and respond to requests, ② display dynamic pages
- JSP container: used to put index The java code in the JSP file is translated into Servlet code.
Description: index JSP file contains html language statically displayed and some java class code, but the java code in the file cannot be directly executed by tomcat, so it needs to be translated into executable code mode first, that is, into servlet code format.
- Servlet container: the servlet code is processed by the script named Catalina.
Description: use catalina to process the servlet code translated by JSP container.
General description: (how to connect the components) If users need to log in to Alipay to view personal information, through the nginx Port 80 of the service, requesting access to dynamic requests, nginx Reverse proxy requests to tomcat Service port 8080, then tomcat Received the user's request, Request to Web There is in the container index.jsp File, which exists java Code, which needs to process dynamic requests, tomcat Just read the java Code, but java Code cannot be tomcat distinguish, So you need to use JSP The container will index.jsp In the file java Code, translated as servlet Code, translated into servlet Code, you need to use servlet Container for disposal servlet code. that selvlet The container will pass catalina Script execution servlet code. After execution, use api The interface calls the corresponding Alipay application, Alipay will call after receiving the user's request mysql The 3306 port of the database confirms the data, and finally returns the data to the user.
3. Tomcat processing request process
- The port of Tomcat is 8080, but it is not the main process of Tomcat that monitors the port of 8080, but the connector of connector (written in java) that monitors it.
- You cannot view the tomcat port using netstat -natp |grep tomcat. You need to use: netstat -natp |grep 8080 to view
Tomcat functional components
Service: web services provided externally, mainly including two core components, connector and container, and other functional components. Tomcat can manage multiple services, and each service is independent of each other.
- Connector: it is responsible for receiving and responding to external requests. It is the transportation hub between Tomcat and the outside world. The listening port receives external requests, passes them to the container for business processing after processing, and finally responds to the outside world after processing.
- Container: responsible for internal processing of business logic. It is composed of four containers: Engine, Host, context and wrapper, which are used to manage and call servlet related logic.
Container structure analysis:
Each Service will contain a container. A container contains four sub containers.
- **Engine engine: * * used to manage multiple virtual hosts. A service can only have one engine at most.
- **Host:** represents a virtual host, which can also be called a site. You can add a virtual host by configuring the host.
- **Context:** represents a web application, including multiple servlet wrappers, which are used to connect the Host project and servlet container
- Wrapper: wrapper, the bottom layer of the container. Each wrapper encapsulates a servlet, which is responsible for the creation, execution, and destruction of object instances.
Engine, Host, context and wrapper belong to parent-child relationship
User request process Users access web content and apply for dynamic access requests through nginx Port 80 reverse proxy to tomcat 8080 port of. here we are tomcat Later, by connector(In the connector) Coyote(java Frame) listening. After receiving the request, submit the request to container(In container) engine(Engine) for processing, engine It is the power core of container operation. be based on engine Support, there will be a lot of running in the container host Virtual hosts (projects). There will also be many projects in these virtual hosts, and then through context(Current program environment) connected to servlet Container. servlet Return to after processing context. context Then return to engine，engine Then return to the port, and the port finally shows the page to the user first
Tomcat: a Web application service
Location of Tomcat: Generally speaking, it is a dynamic processing service after Nginx.
Tomcat function: as a platform for the execution and continuous operation of applications developed by java class language.
Tomcat components: Web container, JSP container, Servlet container
Tomcat workflow: receive the 80 port of nginx - "tomcat8080 port is monitored by the connector" - "engine given to the container" - "Host project (in webapps, the decompressed code of the corresponding project) -" pass the code and connect through the context "-" connect the environment of the application, and finally execute the servlet code (dynamic request task) - "finally, either connect to the database, Or directly return to nginx - "show it to users.
2, Deploy Tomcat
1. Environment deployment - JDK
Turn off firewall
Place the required installation package in the /opt directory
View the java version
java -version #View version
Install jdk environment package
rpm -ivh jdk-8u201-linux-x64.rpm #rpm installation
Set the environment variables of JDK
vim /etc/profile or vim /etc/profile.d/java.sh #Modify configuration file export JAVA_HOME=/usr/java/jdk1.8.0_201-amd64 #set up path export CLASSPATH=.:$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib/dt.jar #Set execution path export PATH=$JAVA_HOME/bin:$PATH #Setting environment variables source /etc/profile or source /etc/profile.d/java.sh #Reload environment variables
Check the java version again
2. Install and start Tomcat
Unzip the tomcat package
Cut the unzipped package into the /usr/local directory and rename it tomcat
View tomcat file
If we want to implement and continuously run one java Develop application services. After simple configuration, you can directly war Package jar Bag, put into webapps Medium, let's make tomcat function. Description of main catalogue 1,bin :Storage startup and shutdown Tomcat Script file of, the most commonly used are: catalina.sh , startup.sh , shutdown.sh 2,conf: deposit Tomcat Various configuration files of the server are commonly used server.xml,context.xml,tomcat-users.xml,web.xml 3,lib: deposit Tomcat Server's jar Packages, generally do not make any changes, unless connected to third-party services, such as redis，Then you need to add the corresponding jar Package. 4,logs:deposit Tomcat journal 5,temp:deposit Tomcat Files generated at runtime ****6,webapps:Directory for storing project resources 7,work: Tomcat Working directory, general cleanup Tomcat It will be used when caching Tomcat Detailed explanation of configuration file 1,catalina.policy :Permission control profile 2,catalina.properties: Tomcat Property profile for 3,context.xml : Context profile 4,logging.properties:Log related configuration files ***5,server.xml : The main configuration file can be modified through the configuration file tomcat Start port, website directory, virtual host, start https Other functions 6,tomacat-user.xml/.xsd: manage user profile 7,web.xml: tomcal of servlet,servlet-mapping,filter,MIME And other related configurations
Put the startup script into the environment for easy startup
Background start /usr/local/tomcat/bin/startup.sh or /usr/local/tomcat/bin/catalina.sh start Foreground start(The terminal is turned off, tomacat Stop operation) /usr/local/tomcat/bin/catalina.sh run close /usr/local/tomcat/bin/shutdown.sh Put the startup and shutdown scripts into the environment ln -s /usr/local/tomcat/bin/startup.sh /usr/local/bin ln -s /usr/local/tomcat/bin/shutdown.sh /usr/local/bin
Page visit: 188.8.131.52:8080
This page is also in tomcat Is running as a project, and the path is:/usr/local/tomcat/ROOT/ The following file
3. tomcat startup optimization
Optimize tomcat startup speed
The speed of starting Tomcat directly is very fast, but after running the project in tomcat, the startup is very slow (40G may start for 10 minutes).
When jar packages and war packages in java are placed in /webapps, the tomcat service (shutdown.sh and startup.sh) needs to be restarted. The purpose of restarting tomcat is to enable the tomcat ring to reload and recognize these java codes in the /webapps directory.
vim /usr/java/jdk1.8.0_201-amd64/jre/lib/security/java.security #Modify the configuration parameters of jdk
- urandom: indicates that the random pool is larger
3, Tomcat virtual host configuration
The concept of virtual host: it simulates multiple channels (functions)
Advantages: make full use of resources, convenient management, reduce the complexity of the architecture, and facilitate customized "capacity expansion" (create multiple virtual hosts)
Disadvantages: it requires the support of other resources, consumes the same network resources, and has a single point of failure
Virtual host in nginx: Based on different IP, different domain names, and different ports. (in the configuration file, each server is a virtual host)
Virtual hosts in Tomcat: use one Tomcat service to run multiple virtual hosts and access different projects through different virtual hosts. (in the configuration file, each host is a virtual host)
1. Create project catalog file
First, create two Host virtual hosts, one ydq project and one benet project
Create a page file for the project
2. Modify Tomcat main configuration file: server.xml
Find master profile
Introduction to the main contents of the configuration file (connector)
Add the contents of ydq project and benet project
<Host name="www.ydq.com" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false"> <Context docBase="/usr/local/tomcat/webapps/ydq" path="" reloalable="true" /> </Host> <Host name="www.benet.com" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false"> <Context docBase="/usr/local/tomcat/webapps/benet" path="" reloalable="true" /> </Host> Profile introduction Host name:host name appBase: Tomcat Program working directory, i.e. storage web Directory of application, relative path: webapps，Absolute path:/usr/local/tomcat/webapps unpackWARs:Enable this webapps Time is right WAR Expand the archive file in format first autoDeploy:stay Tomcat Placed in the running state appBase Whether the application Chengxi in the directory is updated xmlValidation:Verify or not xml Sign of effective inspection xmlNamespaceAware:Whether to enable command space, set this value to xmlValidation by true，express web.xml Document execution validity verification docBase:Corresponding web The storage location of the application can also use a relative path, and the starting path is context Belonging to Host in appBase Defined path path: relative web Server versus path URI,If it is empty, it means webapps Root path of/ reloadable:Allow reloading this context dependent web Class of the application.
Turn off and on tomcat service
3. Client browser access
Why do I need to add port 8080 when visiting the website? Because the default port of the web page is 80, you need to add a port to access it tomcat.
Configure DNS on the client
Browser search: www.ydq.com:8080
Browser search: www.benet.com:8080
Internal data flow diagram of Tomcat server
In the configuration file Host Project format <host name> Start with <Contet......../> Configure how to connect OST Location of the operating environment (pointing to web) </host> Indicates the end of the project
4, Tomcat optimization
The default configuration under the default installation is not suitable for the production environment. It may frequently fake death and need to be restarted. Only through continuous pressure test optimization can it run with maximum efficiency and stability. The optimization mainly includes three aspects, namely, operating system optimization (kernel optimization), Tomcat configuration file parameter optimization, and Java virtual machine optimization.
The optimized configuration file is: /usr/local/tomcat/conf/server Conf, the optimization direction is the Connector container.
1. Common optimization related parameters are as follows: Tomcat configuration file parameters
[maxThreads]: Tomcat uses threads to process each request received. This value represents the maximum number of threads that Tomcat can create. The default value is 200.
[minSpareThreads]: minimum number of idle threads. The number of initialized threads at startup indicates that so many empty threads are opened to wait even if no one is using them. The default value is 10
[maxSpareThreads]: the maximum number of standby threads. Once the created thread exceeds this value, Tomcat will close the socket thread that is no longer needed. The default value is -1 (unlimited), which generally does not need to be specified.
[URIEncoding]: specify the URL encoding format of Tomcat container. The language encoding format is not as convenient as other Web server software configuration, and it needs to be specified separately.
[connectionTimeout]: network connection timeout, unit: milliseconds. Setting to 0 means no timeout. If this setting has hidden dangers, it usually defaults to 20000 milliseconds.
[enableLookups]: whether to reverse check the domain name to return the host name of the remote host. The value is true or false. If it is set to false, the IP address will be returned directly. In order to improve processing capacity, false should be set.
[disabkeUploadTimeout]: whether to use the timeout mechanism for uploading. It should be set to true
[connectionUploadTimeout]: upload timeout. After all, file upload may take more time. This pattern requires your own business to choose, so that the servlet has a longer time to complete its execution. It will take effect only when it is configured and used together with the previous parameter.
[accpetCount]: Specifies the maximum column length of incoming connection requests when all available threads for processing requests are used. Requests exceeding this number will not be processed. Your default is 100.
[compression]: whether to perform GZIP compression on the corresponding data. off: indicates hexadecimal compression, on: indicates that compression is allowed (the text will be compressed), force: indicates that compression is performed in all cases. The default value is 0ff. Compressed data can effectively reduce the size of the compression surface, which can generally be reduced by about 1/3, saving bandwidth.
[compressionMinSize]: indicates the corresponding minimum value of compression. Only when the corresponding message size is greater than this value, the message will be compressed. If the compression function is enabled, the default value is 2048
[compressableMimeType]: compression type, which specifies the types of files in the heap for data compression
[noCompressionUserAgents= "gozilla,traviata"]: for the following browsers, compression is not enabled.
2. Optimize configuration
Restart the tomcat service. The configuration can be completed normally.
Tomcat can be used as an environment for running java code. As long as the Java source code (.Class executable class file) or war package or jar package is placed in /webapps, when Tomcat starts, it can decompress and run these applications placed in /webapps (just modify the configuration file: server.xml)
engine engine--->Host--->context--->servlet(Calling the application's java Environment in which code performs dynamic operations)
1. What are the tomcat components, from entry to processing
Server: the server element is at the top level and represents the entire Tomca container, so it must be server The only outermost element in XML. A server element can have one or more service elements. The main task of server is to provide an interface for clients to access this service set. At the same time, maintain the declaration cycle of all its services, including how to initialize, how to end the service, and how to find the service that the client wants to access.
Service: the function of service is to report a layer outside the connector and engine, assemble them together, and provide services externally. A service can contain multiple connectors, but only one engine. The function of connector is to receive requests from the client, the function of engine is to process requests received, and TTomcat can provide multiple services. Different services listen to different ports.
Connector: connector, coyo http/1.1 8080 port
Engine: container engine, which is a core component for managing and running containers (container: web container, jsp container, servlet container)
Host: it needs to connect with the java running environment - "connect to the java running environment through context"
Context: the context element represents a Web application running on a specific virtual Host. Each Web application is based on the WAR file, or the corresponding directory after extracting the WAR file (here referred to as the application directory). Context is a sub container of the Host, and any number of context elements can be defined in each Host.
servlet: the core component for managing calls and running java code
2. Tomcat virtual host
On service XML. You only need to configure the <context... / > section. This configuration is used to determine how Tomcat manages Java applications + how to dock and connect Java applications.
3. Tomcat optimization
① Optimization in the configuration file: we will optimize in the connector connection configuration end, and the optimization content includes: how to better wait for requests, how to allocate thread resources, memory resources, queues, connection numbers, and timeout time. Startup time optimization (startup time optimization is JDK optimization. Enter /var/java/jdk xxxxx/security/java.security startup thread /dev/random - > /dev/random optimization)
② JVM Optimization: -Xms -Xmx optimization - "means minimum / maximum memory optimization -----" simply understood as -Xms -Xmx is the optimization of the minimum and maximum memory resources used by applications.
③ GC garbage collection optimization - "is because when java applications are in Tomcat, when the running thread and process resources of the application exit, some resource fragments will be left. GC specifies the recycling of these resource fragments.