Tomcat deployment and optimization

Table of contents

 1. Introduction to Tomcat

Two, the composition of Tomcat

3. Tomcat functional component structure

4. Tomcat request process

5. Tomcat service deployment

6. Tomcat virtual host configuration

Seven, Tomcat optimization

1. Tomcat configuration file parameter optimization

2. JVM optimization


 1. Introduction to Tomcat

        Tomcat is developed in Java language . The Tomcat server is a free and open source web application server. It is a core project in the Jakarta project of the Apache Software Foundation and is jointly developed by Apache, Sun and some other companies and individuals.

        Tomcat is a lightweight application server. It is widely used in small and medium-sized systems and occasions where 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 as web servers such as Apache or Nginx, it has the function of processing HTML pages. However, because its ability to process static HTML is far less than that of Apache or Nginx, Tomcat is usually used as a Servlet and JSP container. backend .

Two, the composition of Tomcat

Tomcat consists of a series of components, of which there are three core components

  • Web container: completes the function of the web server.
  • Servlet container: The name is catalina, which is used to process Servlet code.
  • JSP container: used to translate JSP dynamic web pages into Servlet codes.

        So Tomcat is a Web application server and also a Servlet/JSP container. As a Servlet container, Tomcat is responsible for processing the client's .jsp dynamic page request, sending the request to the Servlet, and sending the Servlet's response back to the client.

What are servlets?
        Servlet is the abbreviation of Java Servlet. It can be understood as a service connector, a server-side program written in Java, and has the characteristics of being independent of platforms and protocols. Simple understanding: servlet is a middleware, including interfaces and methods. Connect the client to the database to realize the creation of dynamic web pages.

What is JSP?
        The full name of JSP is Java Server Pages, which is a dynamic web development technology. It uses JSP tags to insert Java code in HTML web pages. Tags usually start with <% and end with %>.
        JSP is a Java servlet primarily used to implement the user interface portion of a Java web application.
        JSP takes user input data through web page forms, accesses databases and other data sources, and then dynamically creates web pages.

3. Tomcat functional component structure

        There are two core functions of Tomcat, the Connector responsible for receiving and feeding back external requests , and the Container responsible for processing requests . Among them, the connector and the container complement each other and together constitute the basic web service Service. Each Tomcat server can manage multiple Services.

  • Connector: Responsible for receiving and responding to external requests. It is the communication hub between Tomcat and the outside world. The listening port receives external requests, processes the requests and passes them to the container for business processing, and finally responds to the outside world with the processed results of the container.
  • Container: Responsible for internal processing of business logic. Its interior consists of four containers, Engine, Host, Context and Wrapper, which are used to manage and invoke Servlet-related logic.
  • Service: Web service provided externally. It mainly includes two core components, Connector and Container, and other functional components. Tomcat can manage multiple services, and each service is independent of each other.

Container structure analysis

Each Service will contain a Container container, which contains 4 sub-containers:

  1. Engine: Engine, used to manage multiple virtual hosts, a Service can only have at most one Engine;
  2. Host: Represents a virtual host, which can also be called a site, and a site can be added by configuring the Host;
  3. Context: represents a Web application, including multiple Servlet wrappers;
  4. 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, these four containers belong to parent-child relationship.
        One container engine can manage multiple virtual hosts; each virtual host can manage multiple web applications; each web application will have multiple Servlet wrappers.

4. Tomcat request process

1. The user enters the URL in the browser, and the request is sent to the local port 8080, and is obtained by the Connector listening there;

2. The Connector hands over the request to the Engine (Container) of the Service where it is located, and waits for the response from the Engine;

3. The request is called layer by layer among the four containers of Engine, Host, Context, and Wrapper, and finally the corresponding business logic, data storage, etc. are executed in the Servlet.

4. After execution, the request response is returned layer by layer between the Context, Host, and Engine containers, and finally returned to the Connector, and returned to the client through the Connector.

5. Tomcat service deployment

Before deploying Tomcat, jdk must be installed, because jdk is a necessary environment for Tomcat to run.

 1. Turn off the firewall and transfer the software package required to install Tomcat to the /opt directory

systemctl stop firewalld
systemctl disable firewalld
setenforce 0

2. Install JDK

CLASSPATH: When compiling and running a Java program, JRE will search for the required (.class) files in the path specified by this variable.
JDK: java development kit (java development tool)
JRE: java runtime environment (java runtime environment)
JVM: java virtuak machine (java virtual machine), so that java programs can run class files on multiple platforms.

cd /opt
rpm -qpl jdk-8u201-linux-x64.rpm 
rpm -ivh jdk-8u201-linux-x64.rpm 

3. Set JDK environment variables

#添加java环境变量配置文件
vim /etc/profile.d/java.sh
export JAVA_HOME=/usr/java/jdk1.8.0_201-amd64
export JRE_HOME=$JAVA_HOME/jre
export CLASSPATH=.:$JAVA_HOME/lib:$JRE_HOME/lib
export PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$PATH

#启用并查看java版本
source /etc/profile.d/java.sh
java -version

4. Test java environment

(1) First use a text tool to write java source code, such as Hello.java;
(2) In the command line, enter javac Hello.java to compile the source code and generate a class bytecode file;
(3) After the compilation is completed , if there is no error message, enter the command: java Hello (prefix name), run the class bytecode file, the bytecode will be interpreted and run by the JVM, and "Hello World" will be printed.

vim Hello.java

public class Hello {			
  public static void main(String[] args){
    System.out.println("Hello world!");
  }
}

javac Hello.java
java Hello

5. Install Tomcat

cd /opt
tar zxvf apache-tomcat-9.0.16.tar.gz
mv apache-tomcat-9.0.16 /usr/local/tomcat

Main Directory Description

bin: store script files for starting and shutting down Tomcat, such as catalina.sh, startup.sh, shutdown.sh;
conf: store various configuration files of the Tomcat server, such as the main configuration file server.xml and the application default deployment description file web .xml;
lib: the jar package that stores the library files needed for Tomcat to run, and generally does not make any changes;
logs: stores the logs when Tomcat is running;
temp: stores the files generated when Tomcat is running;
webapps: stores Tomcat's default Web application project resources directory;
work: the working directory of Tomcat, which stores the generated and compiled files of the Web application code;

6. Start and shut down Tomcat

way to start

        Background start:         /usr/local/tomcat/bin/startup.sh 
                            or /usr/local/tomcat/bin/catalina.sh start

        Foreground start:         /usr/local/tomcat/bin/catalina.sh run

The way to close                 /usr/local/tomcat/bin/shutdown.sh

(1) Start in the background, run the startup.sh file in the bin directory

jps can view the running process of java program

(2) Background start, ./catalina.sh start

(3) Foreground startup, ./catalina.sh run (will display startup information)

Shut down, run the shutdown.sh file in the bin directory

5. Optimize tomcat startup speed

        The first time you start tomcat, you may find that Tomcat starts very slowly. By default, it may take tens of seconds. You can modify the jdk parameters to change it.

vim /usr/java/jdk1.8.0_201-amd64/jre/lib/security/java.security

#在约117行处修改修改
securerandom.source=file:/dev/urandom

#重启
/usr/local/tomcat/bin/shutdown.sh 
/usr/local/tomcat/bin/startup.sh 

Explain that
the reason why tomcat starts slowly is that the random number generation is blocked, and the reason for being blocked is the size of the entropy pool.

  • /dev/random: blocking type, reading it will generate random data, but the data depends on the entropy pool noise, when the entropy pool is empty, the read operation on /dev/random will also be blocked.
  • /dev/urandom: A non-blocking random number generator that reuses data in the entropy pool to generate pseudo-random data. This means that read operations on /dev/urandom will not block, but the entropy of its output may be less than that of /dev/random. It can be used as a pseudo-random number generator for generating low-strength passwords and is not recommended for generating high-strength long-term passwords.

        The Linux kernel uses entropy to describe the randomness of data. Entropy is a physical quantity that describes the degree of chaos and disorder of a system. The greater the entropy of a system, the worse the order of the system, that is, the greater the uncertainty. In informatics, entropy is used to characterize the uncertainty of a symbol or system. The greater the entropy, the less useful information the system contains and the greater the uncertainty. Computers are inherently predictable systems, therefore, it is impossible to generate truly random numbers with computer algorithms. But the environment of the machine is full of various noises, such as the time when the hardware device is interrupted, the time interval when the user clicks the mouse, etc. are completely random and cannot be predicted in advance. The random number generator implemented by the Linux kernel uses these random noises in the system to generate high-quality random number sequences. The kernel maintains an entropy pool that collects ambient noise from device drivers and other sources. Theoretically, the data in the entropy pool is completely random, and it is possible to generate a sequence of true random numbers. To keep track of the randomness of the data in the entropy pool, the kernel will estimate the randomness of the data when it is added to the pool, a process called entropy estimation. The entropy estimate describes the number of random numbers contained in the pool, with a larger value indicating better randomness of the data in the pool.

6. After startup, test access to tomcat service

6. Tomcat virtual host configuration

        In many cases, the company will have multiple projects that need to be run. Generally, multiple Tomcat services will not be run on one server, which will consume too many system resources. At this point, you need to use the Tomcat virtual host. For example, now add two domain names www.abc.com and www.def.com, hoping to access different project content through these two domain names.

1. Create kgc and benet project directories and files

mkdir /usr/local/tomcat/webapps/abc
mkdir /usr/local/tomcat/webapps/def
echo "This is abc page!" > /usr/local/tomcat/webapps/abc/index.jsp
echo "This is def page!" > /usr/local/tomcat/webapps/def/index.jsp

2. Modify the Tomcat main configuration file server.xml

Host 
name
: host name
appBase : Tomcat program working directory, that is, the directory where web applications are stored; the relative path is webapps, and the absolute path is /usr/local/tomcat/webapps
unpackWARs : whether to archive files in WAR format when enabling this webapps Deploy first; the default is true
autoDeploy : whether the application files placed in the appBase directory are automatically deployed when Tomcat is running; the default is true
xmlValidation : whether to verify the flag for validating the xml file
xmlNamespaceAware : whether to enable xml naming space, set this value and xmlValidation to true, indicating that the validity check is performed on the web.xml file

Context
docBase
: the storage location of the corresponding web application; a relative path can also be used, the starting path is the path defined by appBase in the Host to which this Context belongs;
path : URI relative to the root path of the web server; if it is empty "" , it represents the root path of this webapp/;
reloadable: whether to allow reloading of the class of this context-related web application; the default is false

​​​​​​​vim /usr/local/tomcat/conf/server.xml

<!--在约165行前插入-->

<Host name="www.abc.com" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
    <Context docBase="/usr/local/tomcat/webapps/abc" path="" reloadable="true" />
</Host>

<Host name="www.def.com" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
    <Context docBase="/usr/local/tomcat/webapps/def" path="" reloadable="true" />
</Host>

3. Restart tomcat, add domain name resolution and access test

/usr/local/tomcat/bin/shutdown.sh
/usr/local/tomcat/bin/startup.sh

echo "192.168.116.10 www.abc.com www.def.com" >> /etc/hosts

Seven, Tomcat optimization

        The default configuration of Tomcat installed by default is not suitable for the production environment. It may frequently experience suspended animation and need to be restarted. Only through continuous stress testing and optimization can it run at the highest efficiency and stably.

        Optimization mainly includes three aspects: operating system optimization (kernel parameter optimization), Tomcat configuration file parameter optimization , and Java virtual machine (JVM) tuning .

1. Tomcat configuration file parameter optimization

Common optimization related parameters

redirectPort If the protocol supported by a connector is HTTP, when receiving an HTTPS request from the client, it will be forwarded to port 8443 defined by this property.
maxThreads Tomcat uses threads to process each request it receives. This value indicates the maximum number of threads that Tomcat can create, that is, the maximum number of concurrent connections supported. The default value is 200.
minSpareThreads The minimum number of idle threads, the number of threads initialized when Tomcat starts, means that so many idle threads are waiting even if no one is using it, the default value is 10.
maxSpareThreads The maximum number of standby threads. Once the created threads exceed this value, Tomcat will close the socket threads that are no longer needed. The default value is -1 (generally do not need to be specified).
processorCache Process buffer, which can improve concurrent requests. The default value is 200. If there is no limit, it can be set to -1. Generally, the value of maxThreads or -1 is used.
URIEncoding Specifies the URL encoding format of the Tomcat container. UTF-8 is generally used as the default encoding for websites.
connnectionTimeout Network connection timeout, unit: millisecond, setting it to 0 means never timeout, this setting has hidden dangers. Usually the default of 20000 milliseconds is fine.
enableLookups Whether to 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, it will directly return the IP address, in order to improve the processing capacity, it should be set to false.
disableUploadTimeout Whether to use a timeout mechanism when uploading. Should be set to true.
connectionUploadTimeout Upload timeout time. After all, file upload may take more time. You can adjust this according to your own business needs so that the Servlet has a longer time to complete its execution. It needs to be used together with the previous parameter to take effect .
acceptCount Specifies the maximum queue length of incoming connection requests when all available threads for processing requests are used. Requests exceeding this number will not be processed. The default is 100.
maxKeepAliveRequests Specify the maximum number of requests for a persistent connection. The default persistent connection is open. When it is set to 1, it means that the persistent connection is closed; when it is -1, it means that the number of requests is unlimited.
compression Whether to perform GZIP compression on the response data, off: indicates that compression is prohibited; on: indicates that compression is allowed (text will be compressed), force: indicates that compression is performed in all cases, the default value is off, and the page can be effectively reduced after compressing the data Generally, the size can be reduced by about 1/3 to save bandwidth.
compressionMinSize Indicates the minimum value of the compressed response. Only when the size of the response message is greater than this value, the message will be compressed. If the compression function is enabled, the default value is 2048.
compressableMimeType Compression type, specify which types of files are compressed.
noCompressionUserAgents="gozilla, traviata"

Compression is not enabled for the following browsers

(If static and dynamic separation processing has been performed, data such as static pages and pictures do not need to be processed by Tomcat, so do not configure compression in Tomcat.)

vim /usr/local/tomcat/conf/server.xml
......
<Connector port="8080" protocol="HTTP/11.1" 
connectionTimeout="20000" 
redirectPort="8443" 
minSpareThreads="50" 
enableLookups="false" 
disableUploadTimeout="true" 
acceptCount="300" 
maxThreads="500" 
processorCache="500"
URIEncoding="UTF-8" 
maxKeepAliveRequests="100"
compression="on" 
compressionMinSize="2048" 
compressableMimeType="text/html,text/xml,text/javascript,text/css,text/plain,image/gif,image /jpg,image/png"/>

2. JVM optimization

Common parameters

-server Be sure to use it as the first parameter, for better performance on multiple CPUs.
-Xms The size of the initial Java initialization heap is the minimum memory allocated to the JVM. When the CPU performance is high, this value should be set larger.
-Xmx The size of the maximum Java heap is the maximum memory allocated to the JVM, which depends on the size of the physical memory of the hardware. It is recommended to set -Xms and -Xmx to the same value, both of which are half of the physical memory. Its purpose is to waste resources without having to re-partition the size of the heap area after the java garbage collection mechanism has cleaned up the heap area.
-Xmn The memory size of the new generation is officially recommended to be 3/8 of the entire heap.
-XX:ParallelGCThreads Configure the number of threads of the parallel collector, that is: how many threads perform garbage collection together at the same time. It is recommended that this value be equal to the number of CPUs.
-XX:PermSize Set the initial value of the non-heap memory, that is, the size of the permanent generation memory, which is 1/4 of the physical memory by default.
-XX:MaxPermSize The maximum non-heap memory size, that is, the maximum persistent generation memory size, defaults to 14 of the physical memory.

        The heap area is further subdivided into: Cenozoic, Mesozoic, and Old.
        The memory space occupied by each new object in java is the space of the new generation. When the java garbage collection mechanism recycles resources in the heap area, those resources that have not been recovered in the new generation will be transferred to the Mesozoic generation, and those in the Mesozoic generation will be transferred. to the old generation.
        The entire JVM heap size = new generation size + old generation size + permanent generation size

        The non-heap memory will not be processed by the java garbage collection mechanism, and the sum of the maximum heap memory and the maximum non-heap memory cannot exceed the available memory of the operating system.


        The XMX and XMS settings are as large, and the MaxPermSize and MinPermSize settings are as large, which can reduce the pressure brought by the scaling heap size.

-Djava.awt.headless=true Avoid the failure to display pictures on Web pages under Linux/Unix environment.
-XX:+DisableExplicitGC It is forbidden to call System.gc() to prevent the JVM of the system from fluctuating greatly due to the ups and downs of the system's JVM due to the wrong call of the gc method, which seriously reduces the system response time.
-XX:+UseParNewGC Use multi-threaded parallel recycling for the new generation to shorten the garbage collection time,
-XX:+UseConcMarkSweepGC The concurrent mark sweep collector, which is an old generation collection algorithm, shortens the time of garbage collection.
-XX:+CMSParallelRemarkEnabled Enables parallel marking, reducing marking stalls.

-XX:+UseCMSCompactAtFullCollection

-XX:CMSFullGCsBeforeCompaction=0

The default values ​​of these two parameters are like this, indicating that the heap is compressed when FullGC is triggered, and memory fragmentation is optimized.
-XX:CMSInitiatingOccupancyFraction=70 CMS garbage collection starts after the application uses 70% of memory.
vim /usr/local/tomcat/bin/catalina.sh

#配置添加在 Tomcat 的 bin 目录下 catalina.sh 里,位置在 cygwin=false 前。

JAVA_OPTS="$JAVA_OPTS -server -Xms2048m -Xmx2048m -Xmn768m -XX:ParallelGCThreads=2 -XX:PermSize=1024m -XX:MaxPermSize=1024m -Djava.awt.headless=true -XX:+DisableExplicitGC" 
cygwin=false

Guess you like

Origin blog.csdn.net/wlc1213812138/article/details/131480626