Tomcat parameterized configuration v1 zero

Posted by DeathStar on Fri, 14 Jan 2022 15:39:18 +0100

1, Tomcat directory structure (taking version 8.5 as an example)

  • Bin directory. The bin directory is mainly used to store tomcat commands. There are two main categories. One is based on sh (linux command), and the other is with bat (windows command).

    Many environment variables are set here,

    For example, you can set JDK path and tomcat path

    startup is used to start tomcat

    shutdown is used to close tomcat

    Modifying catalina can set the memory of tomcat

  • conf directory.

    The conf directory is mainly used to store some configuration files of tomcat.

    server.xml can set the port number, set the domain name or IP, the default loaded item, and request code.

    web.xml can set the file types supported by tomcat.

    context.xml can be used to configure data sources and so on.

    tomcat-users.xml is used to configure and manage the users and permissions of Tomcat.

  • lib directory.

    The lib directory is mainly used to store the jar packages that need to be loaded for tomcat operation.

  • logs directory.

    As the name suggests, this is the directory where the log files are stored.

    The logs directory is used to store the log files generated during the operation of tomcat. It is very important to output the logs on the console. (emptying will not affect the operation of tomcat).

    In the windows environment, the output log of the console is in Catalina. -- * Log file.

    In the linux environment, the output log of the console is in Catalina Out file.

  • temp directory.

    The temp directory stores temporary files generated by tomcat during operation.

    Emptying will not affect the operation of tomcat.

  • webapps directory.

    The webapps directory is used to store applications. When tomcat starts, it will load the applications under the webapps directory. Applications can be published in the form of folders, war packages and jar packages. You can also place the application anywhere on the disk and map it in the configuration file

  • work directory.

    The work directory is used to store the compiled files of tomcat at run time. Clear the work directory and restart tomcat to clear the cache.

2, Modify the memory of the JVM used by tomcat

2.1. Set the memory of the JVM used by Tomcat (before version 8.5)

Modifying Tomcat with linux_ HOME/bin/catalina. SH, add in front

JAVA_OPTS="-Xms512m -Xmx1024m -Duser.timezone=Asia/Shanghai"

windows modify TOMCAT_HOME/bin/catalina.bat, add before

set JAVA_OPTS=-Xms512m -Xmx1024m

2.2. Set the memory of the JVM used by Tomcat (8.5)

Apache-tomcat-8.5.15 is slightly different from the previous version, the configuration mode has changed, and some parameters for the JVM are no longer supported. Therefore, this document mainly introduces how to configure JVM memory parameters on the apache-tomcat-8.5.15 container.

windows

At% Tomcat_ Create the file setenv. In the home% \ bin \ directory bat,

The contents of the document are as follows:

SET JAVA_OPTS=-server -Xms4g -Xmx4g

Or the content is:

SET "JAVA_OPTS=-server -Xms4g -Xmx4g"

For example - server – Xms256m – Xmx1024m

linux

Tomcat does not recommend directly in catalina Instead of configuring variables in SH, it is written in setenv under the same level directory (bin directory) as catalina SHLI.

Then we need to modify setenv SH file (if not, create a new setenv.sh), write (the size can be modified according to your own situation):

export CATALINA_OPTS="$CATALINA_OPTS -Xms1000m"

export CATALINA_OPTS="$CATALINA_OPTS -Xmx6000m"

export CATALINA_OPTS="$CATALINA_OPTS -XX:MaxPermSize=256m"

3, Server XML file configuration

3.1. Several common configuration modifications

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

Is the closed port that tomcat listens on

<Connector connectionTimeout="20000" port="8080"

 protocol="HTTP/1.1" redirectPort="8443"    useBodyEncodingForURI="true"/>

protocol: http protocol. Let's introduce it in detail:

The network protocol used indicates how tomcat accepts and processes client-side requests. "HTTP/1.1" is the default value, equivalent to "org.apache.coyote.http11.Http11Protocol"; And the familiar "AJP/1.3"

After Tomcat 6.0, NIO is also provided, which can effectively improve performance, especially in a large number of web applications such as long connection / data upload + download portocal = "org.apache.coyote.http11.Http11NioProtocol"

tomcat currently supports four IO models: BIO, NIO, NIO2 and APR. the default is BIO. For Internet applications, we should choose between NIO and NIO2, because it can effectively improve performance (mainly concurrency). NIO2 is AIO, which needs JDK 1.7 + and Linux 2.6 + to support.

BIO: JDK 1.5+,tomcat 5.x+

NIO: JDK 1.6+,tomcat 6.x+

NIO2: JDK 1.7+,tomcat 7.x+

Other fields:

connectionTimeout: connection timeout;

Port: listen for requests sent by the browser. If the port is set to 80, the port can be omitted when accessing( http://localhost );

redirectPort: redirection port. When a user requests a resource with http and the resource itself is set to be accessed through https,

At this time, Tomcat will automatically redirect to the https port set by this redirectPort, that is, the port for processing https requests.

<Connector port="8009" protocol="AJP/1.3" redirectPort="8443"/>

This is to accept requests forwarded by other services.

3.2 common parameter configuration table

parameterexplain
minProcessorsThe minimum number of idle connection threads is used to improve system processing performance. The default value is 10
maxProcessorsThe maximum number of connection threads, that is, the maximum number of concurrent requests. The default value is 75
acceptCountThe maximum number of connections allowed should be greater than or equal to maxProcessors. The default value is 100
enableLookupsWhether to reverse query the domain name. The value is: true or false. To improve processing power, it should be set to false
disableUploadTimeoutNetwork connection timeout in milliseconds. Setting to 0 means never timeout. This setting has hidden dangers. It can usually be set to 30000 milliseconds. The parameters related to the maximum number of connections are maxProcessors and acceptCount. If you want to increase the number of concurrent connections, you should increase both parameters at the same time. The maximum number of connections allowed by the web server is also subject to the kernel parameter settings of the operating system, usually about 2000 for Windows and about 1000 for Linux.
maxThreadsMaximum number of threads for client requests
minSpareThreadsNumber of socket threads created during Tomcat initialization
maxSpareThreadsMaximum number of free socket threads for Tomcat connector
enableLookupsIf set to true, domain name resolution is supported, and the ip address can be resolved to the host name
redirectPortWhen a secure channel is required, the client request is forwarded to the redirectPort port based on SSL
acceptAccountThe maximum number of listening port queues. After it is full, the client request will be rejected (not less than maxsparethread)
connectionTimeoutconnection timed out
minProcessorsMinimum number of processing threads at server creation
maxProcessorsMaximum number of simultaneous processing threads on the server
URIEncodingURL unified coding

3.3. Configuration demo

<Connector port="8080" protocol="org.apache.coyote.http11.Http11NioProtocol" 
               connectionTimeout="20000" 
               maxHeaderCount="64" 
               maxParameterCount="64" 
               maxHttpHeaderSize="8192" 
               URIEncoding="UTF-8" 
               useBodyEncodingForURI="false" 
               maxThreads="128" 
               minSpareThreads="12" 
               acceptCount="1024" 
               connectionLinger="-1" 
               keepAliveTimeout="60" 
               maxKeepAliveRequests="32" 
               maxConnections="10000" 
               acceptorThreadCount="1" 
               pollerThreadCount="2" 
               selectorTimeout="1000" 
               useSendfile="true" 
               selectorPool.maxSelectors="128" 
               redirectPort="8443" /> 

4, Tomcat concurrency optimization

4.1. Tomcat concurrency parameters

maxThreads: Maximum number of concurrent requests, when cpu When the utilization rate is high, the number of threads should not be increased,When cpu The utilization rate is not high, most of them are io When blocking the operation of a class, you can increase this value appropriately.
maxSpareThreads: Tomcat Maximum idle of connector socket Number of threads
acceptCount: The number of queued requests accepted when the number of threads processing tasks reaches the maximum
connectionTimeout: Network connection timeout in milliseconds
enableLookups: if it is false Do not proceed DNS Query to improve business capability should be set to false
connectionTimeout: if it is true Upload timeout is disabled

4.2. Tomcat concurrent configuration

Server under conf Configure nodes in the XML file

<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="30000"
redirectPort="8443"
maxThreads="400"
minSpareThreads="50"
maxSpareThreads="200"
acceptCount="400"
enableLookups="false"
disableUploadTimeout="true" />

4.3. Tomcat memory configuration

tomcat generally has a default memory size, and its default value is very small for the whole physical memory. If tomcat memory is not configured, it will greatly waste server resources and affect the performance of the system. Therefore, the memory configuration of tomcat is particularly important for systems with a large number of users.

See above for details

4.4 Tomcat garbage collection

The garbage collection (gc) mechanism is very important. Sometimes the system will overflow memory because the memory is not collected in time, or fail to respond to user requests due to memory saturation. This requires us to clean up the free memory to ensure the normal operation of the system. The optimal configuration of tomcat GC is the key to ensure the normal operation of the system.

4.4.1 object division and management in JVM

JVMs are roughly divided into three types according to the lifetime of the objects running in them. These three different objects are stored in different memory spaces allocated by the JVM from the system. This management method of object storage space is called Generation management method.

Young Generation: used to store "premature death" objects (i.e. transient objects). For example, a temporary object or local variable used when creating an object or calling a method.
Tenured generation: used to store "resident" objects (i.e. objects referenced for a long time). It is often embodied as a global object in a large program or an object used for a long time.
Perm generation: used to store "permanent" objects. These objects manage the classes and methods that run in the JVM.

4.4.2 jvm garbage collection parameters

-verbose:gc: display garbage collection information (display information on the output device when memory recycling occurs in the virtual machine)
UseConcMarkSweepGC: enable this parameter to use parnew & CMS (serial old as the substitute) collector
Max tenuringthreshold: the maximum age for promotion in the old age. The default value is 15. For example, if it is set to 10, the object will be put into the old generation after 10 ordinary GC s.
  -XX:+ExplicitGCInvokesConcurrent: System.gc() can be executed concurrently with the application.
GCTimeRatio: sets the throughput of the system. For example, if it is set to 99, the GC time ratio is 1 / 1 + 99 = 1%, that is, the required throughput is 99%. If not, it will reduce the size of the Cenozoic.
CMSInitiatingOccupancyFraction: the proportion of memory that triggers the CMS collector. For example, 60% means that CMS concurrent collection will start when the memory reaches 60%.
CMSFullGCsBeforeCompaction: set to trigger a memory flush after several CMS garbage collections.
- Xnoclassgc: disable class garbage collection, and the performance will be higher;
- XX:SoftRefLRUPolicyMSPerMB=N: soft reference survives longer in the virtual machine than in the customer set. The clearing frequency can be controlled by the command line parameter - XX: softrefluplolicymspermb =, which can specify the number of milliseconds that the soft reference in the free space per megaheap remains alive (once it is not strong enough), which means that the soft reference in the free space per megaheap will survive for 1 second (after the last strong reference is recycled). Note that this is an approximate value because soft references are cleared only during garbage collection, which does not always occur. The system defaults to one second.

The above are some basic parameter configurations. View the more detailed configuration through JVM memory management - garbage collector parameter refinement, and view the principle through Java garbage collection tuning in Tomcat

4.4.3 Tomcat garbage collection configuration

Tomcat's garbage collection is configured together with the memory settings. The larger the memory and gc settings, the better. A good ratio can improve your system performance in general or even more. The following is the standard configuration of tomcat7 and 16g server physical memory

Catalina under bin Echo using Catalina in bat file_ Base: add the following code to the previous line of "% catalina_base%".
  set JAVA_OPTS=%JAVA_OPTS%
  -server -Xms8192m -Xmx8192m -Xmn1890m -verbose:gc
  -XX:+UseConcMarkSweepGC -XX:MaxTenuringThreshold=5 -XX:+ExplicitGCInvokesConcurrent -XX:GCTimeRatio=19 -XX:CMSInitiatingOccupancyFraction=70 -    XX:CMSFullGCsBeforeCompaction=0 -Xnoclassgc -XX:SoftRefLRUPolicyMSPerMB=0

Some examples:

If the server is running only one Tomcat
If the sub memory is 8G, the general PermSize configuration is mainly to ensure the stability of the system:

JAVA_OPTS="-Dfile.encoding=UTF-8 -server -Xms6144m -Xmx6144m -XX:NewSize=1024m -XX:MaxNewSize=2048m -XX:PermSize=512m -XX:MaxPermSize=512m -XX:MaxTenuringThreshold=10 -XX:NewRatio=2 -XX:+DisableExplicitGC"

If the sub memory is 16G, the general PermSize configuration is mainly to ensure the stability of the system:

JAVA_OPTS="-Dfile.encoding=UTF-8 -server -Xms13312m -Xmx13312m -XX:NewSize=3072m -XX:MaxNewSize=4096m -XX:PermSize=512m -XX:MaxPermSize=512m -XX:MaxTenuringThreshold=10 -XX:NewRatio=2 -XX:+DisableExplicitGC"

If the sub memory is 32G, the general PermSize configuration is mainly to ensure the stability of the system:

JAVA_OPTS="-Dfile.encoding=UTF-8 -server -Xms29696m -Xmx29696m -XX:NewSize=6144m -XX:MaxNewSize=9216m -XX:PermSize=1024m -XX:MaxPermSize=1024m -XX:MaxTenuringThreshold=10 -XX:NewRatio=2 -XX:+DisableExplicitGC"

If it is a development machine

-Xms550m -Xmx1250m -XX:PermSize=550m -XX:MaxPermSize=1250m
parameterexplain
-Dfile.encodingDefault file encoding
-serverThis indicates that this is the configuration applied to the server, and there will be special processing within the JVM
-Xmx1024mSet the maximum available memory of the JVM to 1024MB
-Xms1024mSet the JVM minimum memory to 1024m. This value can be set to the same value as - Xmx to avoid the JVM reallocating memory after each garbage collection
-XX:NewSizeSet younger generation size
-XX:MaxNewSizeSet the maximum younger generation size
-XX:PermSizeSet permanent generation size
-XX:MaxPermSizeSet maximum permanent generation size
-XX:NewRatio=4Set the ratio of young generation (including Eden and two Survivor areas) to lifelong generation (excluding permanent generation). If it is set to 4, the ratio of the younger generation to the lifelong generation is 1:4, and the younger generation accounts for 1 / 5 of the whole stack
-XX:MaxTenuringThreshold=10Set the maximum age of garbage. The default is 15. If it is set to 0, the younger generation objects directly enter the older generation without passing through the Survivor area. For applications with more elderly generations, efficiency can be improved. If this value is set to a larger value, the younger generation objects will be copied many times in the Survivor area, which can increase the survival time of the younger generation and the probability of being recycled in the younger generation.
-XX:+DisableExplicitGCThis will ignore the code that manually calls GC to make system The call to GC () will become an air conditioner and will not trigger any GC at all

4.5. A demo of configuration

Application Security & turn off automatic deployment

Default value:
<Host name="localhost" appBase="webapps"
 unpackWARs="true" autoDeploy="true">
Change to:
<Host name="localhost" appBase="webapps"
 unpackWARs="false" autoDeploy="false" reloadable="false">

maxThreads connection limit modify configuration

Default value:
<!--
 <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
 maxThreads="150" minSpareThreads="4"/>
 -->
Change to:
<Executor
 name="tomcatThreadPool"
 namePrefix="catalina-exec-"
 maxThreads="500"
 minSpareThreads="30"
 maxIdleTime="60000"
 prestartminSpareThreads = "true"
 maxQueueSize = "100"
/>
Parameter interpretation:
maxThreads: The maximum concurrent number is 200 by default, and 500 is generally recommended ~ 800,Judge according to hardware facilities and business
minSpareThreads: Tomcat The number of threads created during initialization. The default setting is 25
maxIdleTime: If the current thread is greater than the initialization thread, the idle thread's survival time, in milliseconds, is 60000 by default=60 second=1 minute.
prestartminSpareThreads: stay Tomcat Initialize when you initialize minSpareThreads Parameter value, if not equal to true,minSpareThreads The value of has no effect
maxQueueSize: The maximum number of waiting queues. If it exceeds, the request will be rejected

Connector parameter optimization configuration

Default value:
<Connector 
 port="8080" 
 protocol="HTTP/1.1" 
 connectionTimeout="20000" 
 redirectPort="8443" 
 />
Change to:
 

<Connector
 executor="tomcatThreadPool"
 port="8080"
 protocol="org.apache.coyote.http11.Http11Nio2Protocol"
 connectionTimeout="60000"
 maxConnections="10000"
 redirectPort="8443"
 enableLookups="false"
 acceptCount="100"
 maxPostSize="10485760"
 maxHttpHeaderSize="8192"
 compression="on"
 disableUploadTimeout="true"
 compressionMinSize="2048"
 acceptorThreadCount="2"
compressableMimeType="text/html,text/plain,text/css,application/javascript,application/json,application/x-font-ttf,application/x-font-otf,image/svg+xml,image/jpeg,image/png,image/gif,audio/mpeg,video/mp4"
 URIEncoding="utf-8"
 processorCache="20000"
 tcpNoDelay="true"
 connectionLinger="5"
 server="Server Version 11.0"
 />
Parameter interpretation:

protocol: Tomcat 8 set up nio2 Better: org.apache.coyote.http11.Http11Nio2Protocol
protocol: Tomcat 6 set up nio Better: org.apache.coyote.http11.Http11NioProtocol
protocol: Tomcat 8 set up APR Fast performance: org.apache.coyote.http11.Http11AprProtocol 
connectionTimeout: Connector Time to wait after accepting a connection(milliseconds),The default value is 60000.
maxConnections: This value indicates the maximum number of socket connection to tomcat upper
enableLookups: Disable DNS query
acceptCount: When tomcat When the number of threads started reaches the maximum, the number of queued requests is accepted. The default value is 100.
maxPostSize: Sets the resolution by the container URL The maximum length of the parameter,-1(Less than 0)To disable this property, the default is 2097152(2M) Please note that, FailedRequestFilter Filters can be used to reject requests that have reached the limit.
maxHttpHeaderSize: http The maximum of the request header information. The part exceeding this length will not be processed. General 8 K. 
compression: Enable GZIP compress on To enable (text data compression) off Is not enabled, force Compress all data
disableUploadTimeout: This flag allows servlet The container uses a different,It is usually long after the data upload connection times out. If not specified,This property is set to true,Indicates that the time-out is disabled.
compressionMinSize: Compression occurs when the minimum data size is exceeded
acceptorThreadCount: Number of threads used to accept connections. How much does this value increase CPU On your machine,Although you will never really need more than 2. There are also many non maintenance connections,You may want to increase this value. The default value is 1.
compressableMimeType: Configure the data type you want to compress
URIEncoding: Websites generally use UTF-8 As the default encoding.
processorCache: The protocol processor caches processor objects to improve performance. This setting determines how many of these objects are cached.-1 It means infinite,The default is 200. If not used Servlet 3.0 Asynchronous processing,The default is the same maxThreads set up. If used Servlet 3.0 Asynchronous processing,The default is to use large maxThreads And the maximum number of concurrent requests expected(Synchronous and asynchronous). 
tcpNoDelay: If set to true,TCP_NO_DELAY Option will be set on the server socket,In most cases, performance is improved. This is the default setting true. 
connectionLinger: Seconds to close when this connector will continue to use the socket. The default value is -1,Disable socket Delay time.
server: hide Tomcat Version information, hidden first HTTP Version information in header

Hide or modify Tomcat version number

 # cd /usr/local/tomcat/lib/
 # unzip catalina.jar
 # cd org/apache/catalina/util
 # vim ServerInfo.properties
 server.info=Apache Tomcat/8.5.16
 server.number=8.5.16.0
 server.built=Jun 21 2017 17:01:09 UTC
 Remove the above or modify the version number.

Delete or disable the default management page and related configuration files

# rm -rf /usr/local/tomcat/webapps/*
# rm -rf /usr/local/tomcat/conf/tomcat-users.xml

Topics: Operation & Maintenance MySQL Back-end