tomcat optimized reality

Keywords: Apache jvm Tomcat Java

Original Link: https://my.oschina.net/u/1590001/blog/268213

Memory is not as good as bad pen. Here's tomcat brain-free optimization

1. Memory settings (VM parameter tuning)
(1). In Windows environment, tomcat is decompressed (start tomcat by executing startup.bat)

Solution:
Modify the file'%TOMCAT_HOME%\bin\catalina.bat',

Add the following settings at the beginning of the file:

1 set JAVA_OPTS=-Xms512m -Xmx512m -XX:PermSize=128M -XX:MaxNewSize=256m -XX:MaxPermSize=512m

Note: Always put catalina.bat first.

(2).Linux environment

Solution:
Modify the file'%TOMCAT_HOME%\bin\catalina.sh',

Add the following settings at the beginning of the file:

 

JAVA_OPTS="-XX:PermSize=64M -XX:MaxPermSize=128m -Xms512m -Xmx1024m -Duser.timezone=Asia/Shanghai"


Note: There are differences between the former and the latter, whether there is a set or not, and whether there are double quotation marks.


Detailed parameters:

-Xms: Set the initial JVM memory size (default is 1/64 of physical memory)
-Xmx: Set the maximum memory that the JVM can use (default is 1/4 of physical memory, recommended: 80% physical memory)
-Xmn: Set JVM minimum memory (128-256m is sufficient, not usually)

When the default free heap memory is less than 40%, the JVM increases the heap to the maximum limit of -Xmx; when the free heap memory is more than 70%, the JVM reduces the minimum limit of heap to -Xms.Therefore, the server generally sets -Xms, -Xmx equal to avoid resizing the heap after each GC.
In larger application projects, the default memory is insufficient and may cause the system to fail.

A common problem is reporting Tomcat memory overflow errors

"java.lang.OutOfMemoryError: Java heap space",

This causes the client to display 500 errors.

-XX:PermSize: Perm's memory size at JVM startup
 -XX:MaxPermSize: Maximum usable Perm memory size (default is 32M)
-XX:MaxNewSize, default 16M

The full name of PermGen space is Permanent Generation space, which refers to the permanent storage area of memory. This memory is mainly stored by JVM for Class and Meta information. Class is placed in PermGen space when it is Loader. It is different from the Heap area where class instances are stored (Instance). GC(Garbage Collection) will not run during the main program run time.Clean up PermGen space,

So if you have CLASS in your app,

A "java.lang.OutOfMemoryError: PermGen space" error is most likely to occur.

For WEB projects, when a jvm loads classes, the number of objects in the permanent field increases dramatically, so that the jvm keeps resizing the permanent field, so you can use more parameter configurations to avoid adjustments.If you use a lot of third-party jar s under WEB APP,

This error message is generated when the size exceeds the default jvm size.
Other parameters:

-XX:NewSize: default is 2M, this value sets large adjustable new object area, reduces the number of Full GC
 -XX:NewRatio: Change the ratio of old and new space, meaning that the new space is one-eighth the size of the old space (default is 8)
-XX:SurvivorRatio: Change the size ratio of the Eden object space to the remaining space, meaning that the Eden object space is two times larger than the remaining space (default value is 10)
-XX:userParNewGC can be used to set up parallel collection [multiple CPU s]
-XX:ParallelGCThreads can be used to increase parallelism [multiple CPU s]
-XXUseParallelGC settings allow parallel cleanup collectors [multiple CPU s]

 

2. Modify tomcat to support NIO

 


Before modification:

 

<Connector port="9091" protocol="HTTP/1.1" 
connectionTimeout="20000" redirectPort="8443" />

 


Modify to a NIO-enabled type, configured as follows:

<Connector port="9091" protocol="org.apache.coyote.http11.Http11NioProtocol" connectionTimeout="20000" redirectPort="8443" />

 

3. Concurrency Settings
The default tomcat configuration, when concurrent testing occurs, may be 30 USER s down.
Add to

maxThreads="600" //Maximum Threads
minSpareThreads="100" //Number of threads created at initialization
maxSpareThreads="500" //Once the thread exceeds this value, Tomcat shuts down unwanted socket threads
acceptCount="700"//Specifies the number of requests that can be placed in the processing queue when all available threads for processing requests are used, and requests that exceed this number will not be processed
connectionTimeout="20000"
redirectPort="8443" />

perhaps

<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"  maxThreads="500"        minSpareThreads="70" maxSpareThreads="500" acceptCount="700"    maxIdleTime="60000" />

 

<Connector executor="tomcatThreadPool" port="9091" protocol="HTTP/1.1"  connectionTimeout="60000" keepAliveTimeout="15000" maxKeepAliveRequests="1"  redirectPort="8443" />

If you are using the AJP protocol, an integrated cluster, then you also need

<Connector port="13000" protocol="AJP/1.3"  executor="tomcatThreadPool"
connectionTimeout="30000" redirectPort="8443" />

This is the best way to have two ports use the same thread pool

 

4.Java Virtual Machine Tuning


The JVM of SUN should be selected. On the premise of meeting the needs of the project, try to select a higher version of JVM. Generally speaking, a higher version of the product will improve in speed and efficiency than a lower version.JDK1.4 has nearly 10%-20% performance improvement over JDK1.3 and JDK1.5 25%-75% performance improvement over JDK1.4.

 

5. Disable DNS queries


server.xml Set enableLookups="false":

enableLookups="false" redirectPort="8443" URIEncoding="UTF-8" acceptCount="1000" />

 


When a web application sends information to the client to be logged, it also logs the IP address of the client or converts a machine name to an IP address by looking up a domain name server.DNS queries require network usage and include the process of obtaining IP from many remote or ineffective servers, which can take time.To eliminate the performance impact of DNS queries, we can turn off DNS queries.

This is done by modifying the enableLookups parameter value in the server.xml file to false.

 

6. Set up to solve random code problems

URIEncoding="UTF-8" />

 

Tomacat7 startup error is as follows (Jar package conflict):

 

The solution is to add <Context>in the context.xml file of Tomacat7 (using the local Jar package)

java.lang.NoSuchMethodException: org.apache.catalina.deploy.WebXml addFilter

<Loader delegate="true" />

 

My tomcat configuration conf/server.xml

<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="9001" shutdown="SHUTDOWN">
  <!-- 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 are 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.catalina.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
  -->
  <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>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this 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-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"  maxThreads="500"        minSpareThreads="70" maxSpareThreads="500" acceptCount="700"    maxIdleTime="60000" />

    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
   
    <Connector port="9091" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

    <Connector port="9091" protocol="HTTP/1.1" maxThreads="700"        minSpareThreads="90" maxSpareThreads="500" acceptCount="900"
    connectionTimeout="30000" redirectPort="8443" />
 -->
    <Connector executor="tomcatThreadPool" port="9091" protocol="HTTP/1.1"  connectionTimeout="60000" keepAliveTimeout="15000" maxKeepAliveRequests="1"  redirectPort="8443" />

    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector 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 JSSE configuration, when using APR, the
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
    <!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 
    <Connector port="11000" protocol="AJP/1.3" redirectPort="8443" />-->

<Connector port="11000" protocol="AJP/1.3"  executor="tomcatThreadPool"
connectionTimeout="30000" redirectPort="8443" />
    <!-- An Engine represents the entry point (within Catalina) that processes
         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 -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat3">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) 
     -->
         <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>

    <!-- 
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"   
channelSendOptions="8" >          
<Manager className="org.apache.catalina.ha.session.DeltaManager"   
expireSessionsOnShutdown="false"   
notifyListenersOnReplication="true" />  

<Channel className="org.apache.catalina.tribes.group.GroupChannel" >  
<Membership className="org.apache.catalina.tribes.membership.McastService"   
address="228.0.0.4"   
port="45564"   
frequency="500"   
dropTime="3000" />  
<Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"   
address="auto"   
port="4000"   
   
selectorTimeout="5000"   
maxThreads="6" />  -->
<!-- timeout="60000" 
<Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter" >  
<Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"  />  
</Sender>  
<Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector" />  
<Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor" />  
<Interceptor className="org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor" />  
</Channel>  

<Valve className="org.apache.catalina.ha.tcp.ReplicationValve" filter="" />  
<Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve" />  

<Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"   
tempDir="/tmp/war-temp/"   
deployDir="/tmp/war-deploy/"   
watchDir="/tmp/war-listen/"   
watchEnabled="false" />  

<Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
filter=".*\.gif;.*\.js;.*\.jpg;.*\.png;.*\.htm;.*\.html;.*\.css;.*\.txt;" />  


<ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener" />  
</Cluster>      
-->  
  

      <!-- Use the LockOutRealm to 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 are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">
    <Context path="" docBase="E:\Clusters\static\" reloadable="true" crossContext="true"/>
        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

      </Host>
    </Engine>
  </Service>
</Server>

 



Reprinted at: https://my.oschina.net/u/1590001/blog/268213

Posted by metrathon on Sat, 14 Sep 2019 20:06:00 -0700