Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Tomcat configuration and Optimization

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the example analysis of Tomcat configuration and optimization, which has a certain reference value, and interested friends can refer to it. I hope you will gain a lot after reading this article.

Service.xml

The Server.xml configuration file is used to configure the entire container.

Elements:

Is the root element of the entire configuration file. Represents the entire Catalina container.

Attributes:

ClassName: implements the class name of the org.apache.catalina.Server interface, and the standard implementation class is the org.apache.catalina.core.StandardServer class.

The Port:Tomcat server listens for commands to shut down the Tomcat server (must)

Shutdown: a command sent to the port to shut down the Tomcat server.

Example:

Elements:

The connector is responsible for receiving the customer's request and sending back the response message to the client.

HTTP Connector:

Attributes:

AllowTrace: whether to allow the TRACE method of HTTP. Default is false.

EmptySessionPath: if set to true, all paths for the user will be set to /, and the default is false.

EnableLookups: call request, getRemoteHost () to perform a DNS query to return the hostname of the remote host, and if set to false, return the IP address directly.

MaxPostSize: specifies the maximum number of requests in POST mode, and defaults to 2097152 if not specified.

Protocol: the value must be HTTP1.1, or AJP/1.3 if the AJP processor is used

ProxyName: if this connector is being used in a proxy configuration, specify this property and return when request.getServerName ()

RedirectPort: if the connector does not support SSL requests, if a SSL request is received, the Catalina container will automatically redirect the specified port number for processing.

Scheme: sets the name of the protocol, which is returned when request.getScheme (). The SSL connector is set to "https". The default is "http".

Secure: you can set it to true in the SSL connector and default to false

URIEncoding: character encoding used to decode URL. The default value is not specified as ISO-8859-1.

UseBodyEncodingForURI: mainly used in Tomcat4.1.x, indicating whether to use the encoding specified in contentType to replace URIEncoding. It is used to decode URI query parameters. Default is false.

XpoweredBy: when true, Tomcat uses the recommended header of the specification to indicate that the specification version of Servlet is supported. The default is false.

AcceptCount: the maximum number of requests queued in the queue when all possible threads are in use. When the queue is full, any requests received will be rejected. The default value is 10.

BufferSize: sets the size of the input stream buffer created by the connector, in bytes. By default, the cache size is 2048 bytes

The list of compressableMimeType:MIME, separated by commas by default. The default value is text/html,text/xml,text/plain

Compression: specifies whether to compress the response data. Off: disable compression, on: allow compression (text will be compressed), force: compression is performed in all cases, default is off

ConnectionTimeout: sets the timeout value for the connection in milliseconds. The default value is 60000 seconds.

DisableUploadTimeOut: allows the Servlet container to execute using a longer connection timeout value so that Servlet has a longer time to complete its execution. The default is false.

The maximum number of maxHttpHeaderSize:HTTP request and response headers in bytes. The default is 4096 bytes.

MaxKeepAliveRequest: the maximum number of pipelines sent by the client before the server is shut down. Default value is 100

MaxSpareThreads: the maximum number of idle threads allowed. The default is 50.

MinSpareThreads: when the connector initiates the number of co-created threads for the first time, ensure that at least so many idle threads are available. The default value is 4

Port: the TCP port number of the server socket listening. The default value is 8080 (required)

SocketBuffer: sets the size of the Socket output buffer (in bytes).-1 forbids buffering. The default value is 9000 bytes.

ToNoDelay: when true, performance can be improved. The default value is true

ThreadPriority: sets the priority of the request processing thread in JVM. The default value is NORMAL-PRIORITY

Example:

AJP Connector:

Used to integrate Apache with Tomcat, and when the Apache receives a request for dynamic content, it sends the request to the AJP connector component listening on this port number through the port number specified in the configuration.

Attributes:

Backlog: the maximum number of queued requests when all possible request processing threads are in use. The default is 10. When the queue is full, any request will be rejected.

MaxSpareThread: the maximum number of idle threads allowed. The default is 50.

MaxThread: maximum number of threads. Default is 200.

MinSpareThreads: set the number of threads created when the connector starts for the first time to ensure that at least so many free threads are available. The default value is 4.

Port: TCP port number of the server socket, default is 8089 (required)

TopNoDelay: when true, performance can be improved. Default is true.

SoTimeout: timeout valu

Example:

Elements:

Handle all requests for a specific Service. Each Service can contain only one Engine element, which is responsible for receiving and processing all requests received by the connector of this Service, sending a response back to the connection, and eventually displaying it on the client. There must be at least one element and at least one attribute whose name matches the name specified by defaultHost.

Attributes:

ClassName: implements the org.apache.catalina.Engine interface. The default implementation class is org.apache.catalina.core.StandardEngine class.

DefaultHost: default hostname, and the value must match the name value of

Name: specifies the logical name of the Engine (required)

JvmRoute: identifiers used in load balancing, must be unique

Example:

Elements:

Represents a virtual host that handles all requests for a specific virtual host

Attributes:

AppBase: sets the application's base directory, absolute path, or pathname relative to% CATALINA_HOME%

AutoDeploy: indicates whether Tomcat is automatically deployed when a new WEB program is opened in the directory specified by appBase. The default value is true.

ClassName: a class that implements the org.apache.catalina.Host interface, and the standard implementation class is the org.apache.catalina.core.StandardHost class

When deployOnStartup:Tomcat starts, whether to automatically deploy all WEB applications in the specified directory with the appBase attribute. The default is true.

Name: network name of the virtual host (required)

Additional attributes supported by the standard Host implementation class org.apahce.catalina.core.StandardHost:

DeployXML: for false, context.xml within the WEB application will not be parsed. The default is true.

UnPackWARs: the virtual host specifies the pathname of the directory used for temporary reads and writes. If not, Tomcat will provide a suitable directory under the% CATALINA_HOME%/work directory.

Example:

Configure the virtual host:

Elements:

A WEB application that handles all requests from the current WEB application, each of which must use a unique context path.

Attributes:

ClassName: the class that implements the org.apache.catalina.Context interface, and the standard implementation class org.apache.catalina.core.StandardContext class

Cookies: whether to apply Cookie to Session. The default is true.

CrossContext: whether cross-domain access is allowed, when true, calling the ServletContext.getContext () method within the program will return the request scheduler of other web programs on a virtual host. The default is false, and the diameter adjustment is returned as null with getContext ().

DocBase: absolute path or relative path relative to the appBase attribute of Host

Privileged: for true, allows Web applications to use the Servlet of the container

Path: specify the context path. Context paths must be unique in a virtual host

Reloadable: when running for true,Tomcat, Tomcat automatically reloads the WEB application if there are changes in the WEB-INF/classes and WEB-INF/lib directories. Although convenient, it is also expensive. The default value is false. We can open the call and close it after it is released.

CacheMaxSize: maximum value of static resource cache in KB. Default is 10240KB.

CachingAllowed: whether static resource caching is allowed. Default is true.

CaseSensitive: the default is true, and the resource file name is case-sensitive. If false, it is case-insensitive.

UnpackWAR: default is true

WorkDir: specifies the directory pathname for temporary read and write to the Servlet within the WEB application. If not set, Tomcat will provide a suitable directory under the% CATALINA_HOME%/work directory

Example:

Arrangement of Tomcat performance optimization scheme

Considering this scenario, you have developed an application with excellent layout design, the latest features, and other excellent features. However, there is a lack of performance, no matter how the application will be rejected by customers. Customers always expect their applications to have better performance.

If you use a Tomcat server in your product, this article will give you several ways to improve the performance of the Tomcat server. Thanks to ITWorld article for providing resources for this article. After reflection, I have learned that the latest Tomcat provides better performance and stability than earlier versions. So use the latest Tomcat version all the time. Now this article uses the following steps to improve the performance of the Tomcat server.

Increase JVM heap memory size

Fix JRE memory leak

Thread pool settings

Compress

Database performance tuning

Tomcat native library

Other options

Step 1-improve JVM stack memory Increase JVM heap memory

If you have used tomcat, it is simply a memory overflow. Usually, this problem occurs in the actual production environment. The reason for this problem is that tomcat uses less memory for processes, which can be solved by configuring TOmcat configuration files (catalina.bat under Windows or catalina.sh under Linux). This solution is achieved by increasing the stack memory of JVM. That is, JVM usually does not invoke the garbage collector, so the server can pay more attention to processing web requests and require it to be completed as soon as possible. To change the file (catalina.sh) in "\ tomcat server folder\ bin\ catalina.sh", below, give the configuration information for this file.

JAVA_OPTS= "- Djava.awt.headless=true-Dfile.encoding=UTF-8-server-Xms1024m-Xmx1024m-XX:NewSize=512m-XX:MaxNewSize=512m-XX:PermSize=512m-XX:MaxPermSize=512m-XX:+DisableExplicitGC"-Xms-specify stack memory for initialization-Xms-specify stack memory for initialization-Xmx-specify maximum stack memory

These configuration changes will not take effect until you restart your Tomcat server. Here's how to handle JRE memory leaks.

Step 2-resolve JRE memory leak

Another major reason for poor performance is memory leaks, as I said before: always use the latest tomcat server for better performance and scalability. Now, this sentence is true. This error can be resolved if we use the latest tomcat version 6.0.26 or later, because it includes a listener to handle memory leaks for JRE and PermGen. The listener used is

You can find the configuration of this listener in the server.xml file, and the server.xml location is in "tomcat project folder/conf/server.xml". Next, we'll look at how to adjust the connection property "maxThreads".

Step 3-Thread Pool Settings

The thread pool specifies the amount of Web request load, so this part should be handled with care for better performance. You can complete the setting by adjusting the connector property "maxThreads". The value of maxThreads should depend on the size of the traffic. If the value is too low, there will not be enough threads to process all requests, and the request will enter the waiting state and will only be processed when one processing thread is released; if set too high, Tomcat will take more time to start. So it depends on us setting the correct value for maxThreads.

In the above configuration, the maxThreads value is set to "250", which specifies the maximum number of concurrent requests that can be processed by the server. If not specified, the default value for this property is "200". Any extra concurrent requests will receive a "connection denied" error until another processing request process is released. The error looks like this

Org.apache.tomcat.util.threads.ThreadPool logFull SEVERE: All threads arecurrently busy, waiting. Increase maxThreads (250) or check the servlet status

If the application prompts the above error, be sure to check whether the error is caused by a single request taking too long. The reason for this problem is that sometimes if the database connection is not released, the process will not process other requests.

Note: if the number of requests exceeds "750", this does not mean that the value of the maxThreads attribute is set to" 750", it is accidentally best to use multiple instances of "Tomcat cluster". That is, if there is a "1000" request, two Tomcat instances set "maxThreads= 1000" instead of maxThreads=1000 in the case of a single Tomcat instance.

In my experience, the exact value can be set by testing it in a variety of environments. Next, let's look at how to compress the MIME type.

Step 4-Compression

Tomcat has an option to set compression in the server.xml configuration file. Compression can be done in connector settings like the following

In the previous configuration, the file is compressed when the size of the file is greater than or equal to 500bytes. If the file reaches its size but is not compressed, set the property compression= "on". Otherwise, the Tomcat default setting is "off". Next we'll look at how to tune the database.

Step 5-Database performance tuning

Tomcat performance degrades while waiting for database queries to be executed. Most applications today use relational databases that may contain "named queries". In that case, Tomcat loads named queries by default at startup, which may improve performance. Another important thing is to ensure that all database connections are properly closed. It is also important to set the correct value for the database connection pool. By value I mean the maximum number of free (maxIdle), maximum number of connections (maxActive), and maximum connection wait time (maxWait) attribute of the Resource element. Because of configuration dependencies and application requirements, I cannot specify the correct value in this article. You can find the correct value by calling the database performance test.

Step 6-Tomcat native library

Tomcat's native library is based on Apache Portable Runtime (Apache Portable Runtime referred to as APR), which provides programmers with strong scalability and performance, and helps to integrate native server technology in product operation to show the best performance. If you want to know the installation instructions, please refer to Tomcat Native Library-(APR) Installation.

Step 7-other options

These options are:

Turn on the browser's cache so that it is faster to read static content stored in the webapps folder, greatly boosting overall performance.

The Tomcat server should be restarted automatically whenever it is powered on.

In general, HTTPS requests are slower than HTTP requests. If you want better security, we still have to choose HTTPS even if it's a little slower.

Set TOMCAT to enable GZIP compression

Brief introduction of principle

HTTP compression can greatly improve the speed of browsing the website. its principle is that after the client requests the corresponding resources from the server, the resource files are compressed from the server and then output to the client, and the browser of the client is responsible for decompressing and browsing.

Compared with the normal browsing process HTML, CSS,Javascript, Text, it can save about 40% of the traffic. More importantly, it can compress dynamically generated web pages, including CGI, PHP, JSP, ASP, Servlet,SHTML and so on, with high compression efficiency.

Configuration method

Future versions of Tomcat5.0 support compressing the output, using the gzip compression format.

Modify% TOMCAT_HOME%/conf/server.xml, and the revision node is as follows:

As you can see from the attributes of the above node, to use the gzip compression function, you need to add the following attributes to the Connector node

Compression= "on" turns on compression

CompressionMinSize= "50" enables compressed output content size. Default is 2KB.

NoCompressionUserAgents= "gozilla, traviata" does not enable compression for the following browsers

Which resource types of compressableMimeType= "text/html,text/xml,text/javascript,text/css,text/plain" need to be compressed

Testing method

With the compression feature TOMCAT enabled, how can we test whether the compression is effective?

First of all, Tomcat determines whether the browser supports compression according to the accept-encoding in the browser request header. If this value contains gzip, it means that the browser supports browsing of gzip compressed content. We can use two methods to verify whether the compression is effective.

You can directly access the server with compression configuration enabled through the browser, and then check the captured packets through the packet grab tool. If there are a lot of content that you do not understand, it means that compression has been enabled.

Simulate the request through the program

Let's write a simple test program in httpclient with the following code:

@ Test public void testGzip () {HttpClient httpClient = new HttpClient (); GetMethod getMethod = new GetMethod ("http://localhost/admin.jsp"); try {getMethod.addRequestHeader (" accept-encoding "," gzip,deflate "); getMethod.addRequestHeader (" user-agent "," Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Alexa Toolbar; Maxthon 2.0) "); int result = httpClient.executeMethod (getMethod); if (result = 200) {System.out.println (getMethod.getResponseContentLength ()) String html = getMethod.getResponseBodyAsString (); System.out.println (html); System.out.println (html.getBytes () .length);}} catch (HttpException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();} finally {getMethod.releaseConnection ();}}

Execute this junit program to see what it outputs, if the output is some garbled, and the length of the printed content is far less than the actual length, it means that our configuration is effective, through some other verification tools, we will find that the browsing speed of the website will be significantly improved.

Note: if you find that the content is not compressed, you can consider resizing the compressionMinSize. If the requested resource is less than this value, compression will not be enabled.

Thank you for reading this article carefully. I hope the article "sample Analysis of Tomcat configuration and Optimization" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report