本文连接:https://blog.csdn.net/zs742946530/article/details/82346707html
性能调优听起来很高大上,上规模的公司都有专业运维,通常这种事情也是由运维来作。不过做为程序猿咱们也要了解其中的参数和设置。java
tomcat性能调优咱们应该作哪些工做呢?web
首先咱们找到tomcat文件目录下的conf文件夹下的server.xml文件。正则表达式
能够从以下几个方面去作工做:express
1、Tomcat的运行模式优化
tomcat的运行模式有三种:1 、BIO 2 、 NIO 3 、APRapache
不过java7以后NIO又作了改进 NIO2(AIO),因此如今有四种模式:浏览器
org.apache.coyote.http11.Http11Protocol - blocking Java connector-----------------------BIO
org.apache.coyote.http11.Http11NioProtocol - non blocking Java connector ------------NIO
org.apache.coyote.http11.Http11Nio2Protocol - non blocking Java connector-----------NIO2
org.apache.coyote.http11.Http11AprProtocol - the APR/native connector.----------------APR缓存
首先咱们先来了解一下这三种模式的区别:tomcat
BIO:tomcat7及tomcat7之前的版本默认的运行模式,性能很是低,没有通过任何优化处理和支持,一个线程一个请求。缺点:并发量高时,线程数较多,浪费系统资源。安全
NIO:是Java SE 1.4及后续版本提供的一种新的I/O操做方式(即java.nio包及其子包)。Java nio是一个基于缓冲区、并能提供非阻塞I/O操做的Java API,所以nio也被当作是non-blocking I/O的缩写。它拥有比传统I/O操做(bio)更好的并发运行性能。
利用Java的异步IO处理,能够经过少许的线程处理大量的请求。
Tomcat8在Linux系统中默认使用这种方式。
Tomcat7必须修改Connector配置来启动:
<Connector port="8080"protocol="org.apache.coyote.http11.Http11NioProtocol"
connectionTimeout="20000" redirectPort="8443"/>
APR
安装起来最困难,可是从操做系统级别来解决异步的IO问题,大幅度的提升性能.
即Apache PortableRuntime,从操做系统层面解决io阻塞问题。
Tomcat7或Tomcat8在Win7或以上的系统中启动默认使用这种方式。
Linux若是安装了apr和native,Tomcat直接启动就支持apr。
具体安装办法 参见这个地址:https://my.oschina.net/lsw90/blog/181161
在那里看咱们的tomcat以何种工做模式启动的啊?
Tomcat启动的时候,能够经过log看到Connector使用的是哪种运行模式:
StartingProtocolHandler ["http-bio-8080"]
StartingProtocolHandler ["http-nio-8080"]
StartingProtocolHandler ["http-apr-8080"]
2、线程池优化
默认的tomcat没有启用线程池,
在tomcat中每个用户请求都是一个线程,因此可使用线程池提升性能。这里前台其实有一个调度线程,而后调度线程会放入线程池内,而后到到必定的时候线程池的任务变成工做线程啊。
怎么启动线程池呢?看以下配置,把Executor节点注释打开,同时在Connector中添加executor=Executor的name
线程池还有如下参数能够配置
Attribute
Description
threadPriority (优先级)
(int)线程的线程优先级执行程序,默认是5(NORM_PRIORITY常数)
daemon(守护进程)
(布尔)是否应该守护程序线程,线程默认是true
namePrefix(名称前缀)
(String) The name prefix for each thread created by the executor. The thread name for an individual thread will be namePrefix+threadNumber
maxThreads(最大线程数)
(int) The max number of active threads in this pool, default is 200
minSpareThreads(最小活跃线程数)
(int) The minimum number of threads always kept alive, default is 25
maxIdleTime(空闲线程等待时间)
(int) The number of milliseconds before an idle thread shutsdown, unless the number of active threads are less or equal to minSpareThreads. Default value is 60000(1 minute)
一个空闲的线程shutsdown以前的毫秒数,除非活动线程的数量不等于minSpareThreads。默认值为60000(1分钟)
maxQueueSize(最大的等待队里数,超过则请求拒绝)
(int) The maximum number of runnable tasks that can queue up awaiting execution before we reject them. Default value is Integer.MAX_VALUE
可运行的最大数量能够排队等待执行的任务以前,咱们拒绝他们。默认值是Integer.MAX_VALUE
prestartminSpareThreads
(是否在启动时就生成minSpareThreads个线程)
(boolean) Whether minSpareThreads should be started when starting the Executor or not, the default is false
minSpareThreads是否应该开始在开始执行程序,默认是false
threadRenewalDelay
(重建线程的时间间隔)
(long) If a ThreadLocalLeakPreventionListener is configured, it will notify this executor about stopped contexts. After a context is stopped, threads in the pool are renewed. To avoid renewing all threads at the same time, this option sets a delay between renewal of any 2 threads. The value is in ms, default value is 1000 ms. If value is negative, threads are not renewed.
。重建线程池内的线程时,为了不线程同时重建,每隔threadRenewalDelay(单位: ms )重建一个线程。默认值为1000 ,设置为负则不重建
3、链接器(Connector)优化
咱们知道TOMCAT_HOME/conf/server.xml能够配置端口,虚拟路径等等 Tomcat相关主要配置。
1.Connector 优化
Connector是链接器,负责接收客户的请求,以及向客户端回送响应的消息。因此 Connector的优化是重要部分。默认状况下 Tomcat只支持200线程访问,超过这个数量的链接将被等待甚至超时放弃,因此咱们须要提升这方面的处理能力。
修改这部分配置须要修改TOMCAT_HOME/conf/server.xml,打开server.xml找到Connector 标签项,默认配置以下:
Xml代码
<Connector port="8080"protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
其中port表明服务接口;protocol表明协议类型;connectionTimeout表明链接超时时间,单位为毫秒;redirectPort表明安全通讯(https)转发端口,通常配置成443。
能够看到除了这几个基本配置外并没有特殊功能,因此咱们须要对 Connector 进行扩展。
其中Connector 支持参数属性能够参考Tomcat官方网站(https://tomcat.apache.org/tomcat-8.0-doc/config/http.html),很是多,因此本文就只介绍些经常使用的。
咱们将 Connector 配置修改成以下:
<Connector port="8080"
protocol="HTTP/1.1"
maxThreads="1000"
minSpareThreads="100"
acceptCount="1000"
maxConnections="1000"
connectionTimeout="20000"
maxHttpHeaderSize="8192"
tcpNoDelay="true"
compression="on"
compressionMinSize="2048"
disableUploadTimeout="true"
redirectPort="8443"
enableLookups="false"
URIEncoding="UTF-8" />
Connector是Tomcat接收请求的入口,每一个Connector有本身专属的监听端口8088端口 接受http请求
Connector有两种:HTTP Connector和AJPConnector
Attribute
Description
allowTrace
A boolean value which can be used to enable or disable the TRACE HTTP method. If not specified, this attribute is set to false.
若是须要服务器可以处理用户的HAED/TRACE请求,这个值应该设置为true,默认值是false
asyncTimeout
The default timeout for asynchronous requests in milliseconds. If not specified, this attribute is set to 10000 (10 seconds).
默认超不时候以毫秒为单位的异步恳求。如果没有指定,该属性被设置为10000(10秒)。
enableLookups
Set to true if you want calls to request.getRemoteHost() to perform DNS lookups in order to return the actual host name of the remote client. Set to false to skip the DNS lookup and return the IP address in String form instead (thereby improving performance). By default, DNS lookups are disabled.
如果你想request.getRemoteHost()的调用 履行,以便返回的长途客户端的实际主机名的DNS查询,则设置为true。设置为false时跳过DNS查找,并返回字符串情势的IP地址(从而提升性能)。默认景象下,禁用DNS查找。
maxHeaderCount
The maximum number of headers in a request that are allowed by the container. A request that contains more headers than the specified limit will be rejected. A value of less than 0 means no limit. If not specified, a default of 100 is used.
容器容许的请求头字段的最大数目。请求中包含比指定的限制更多的头字段将被拒绝。值小于0表示没有限制。若是没有指定,默认设置为100。
maxParameterCount
The maximum number of parameter and value pairs (GET plus POST) which will be automatically parsed by the container. Parameter and value pairs beyond this limit will be ignored. A value of less than 0 means no limit. If not specified, a default of 10000 is used. Note that FailedRequestFilter filtercan be used to reject requests that hit the limit.
将被容器自动解析的最大数量的参数和值对(GET加上POST)。参数值对超出此限制将被忽略。值小于0表示没有限制。若是没有指定,默认为10000。请注意, FailedRequestFilter 过滤器能够用来拒绝达到了极限值的请求。
maxPostSize
The maximum size in bytes of the POST which will be handled by the container FORM URL parameter parsing. The limit can be disabled by setting this attribute to a value less than or equal to 0. If not specified, this attribute is set to 2097152 (2 megabytes).
将被容器以FORM URL参数形式处理的最大长度(以字节为单位)的POST。经过设置此属性的值小于或等于0能够禁用该限制。若是没有指定,该属性被设置为2097152(2兆字节)。上传提交的时候能够用的
maxSavePostSize
The maximum size in bytes of the POST which will be saved/buffered by the container during FORM or CLIENT-CERT authentication. For both types of authentication, the POST will be saved/buffered before the user is authenticated. For CLIENT-CERT authentication, the POST is buffered for the duration of the SSL handshake and the buffer emptied when the request is processed. For FORM authentication the POST is saved whilst the user is re-directed to the login form and is retained until the user successfully authenticates or the session associated with the authentication request expires. The limit can be disabled by setting this attribute to -1. Setting the attribute to zero will disable the saving of POST data during authentication. If not specified, this attribute is set to 4096 (4 kilobytes).
将被容器在FORM或CLIENT-CERT认证中保存/缓冲的POST的最大尺寸(以字节为单位)。对于这两种类型的身份验证,在用户身份验证之 前,POST将被保存/缓冲。对于POST CLIENT-CERT认证,处理该请求的SSL握手和缓冲清空期间,POST将被缓存。对于Form认证,POST将被保存,同时用户将被重定向到登录 表单。POST将被一直保留直到用户成功认证或者认证请求关联的会话超时。将此属性设置为-1能够禁用此限制。将此属性设置为0,POST数据在身份验证 过程当中将不被保存。若是没有指定,该属性设置为4096(4千字节)。
parseBodyMethods
A comma-separated list of HTTP methods for which request bodies will be parsed for request parameters identically to POST. This is useful in RESTful applications that want to support POST-style semantics for PUT requests. Note that any setting other than POST causes Tomcat to behave in a way that goes against the intent of the servlet specification. The HTTP method TRACE is specifically forbidden here in accordance with the HTTP specification. The default is POST
以逗号分隔的HTTP方法列表,经过方法列表,等同于POST方法,request 正文将被解析成请求参数。这在RESTful应用程序要支持以POST式的语义解析PUT请求中是很是有用的。须要注意的是设置其余值(不是POST)会致使Tomcat的行为违反servlet规范的目的。在这里为了符合HTTP规范明确禁止HTTP方法TRACE。默认值是POST
port
The TCP port number on which this Connector will create a server socket and await incoming connections. Your operating system will allow only one server application to listen to a particular port number on a particular IP address. If the special value of 0 (zero) is used, then Tomcat will select a free port at random to use for this connector. This is typically only useful in embedded and testing applications.
TCP端口号,链接器利用该端口号将建立一个服务器套接字,并等待传入的链接。你的操做系统将只容许一个服务器应用程序在一个特定的IP地址侦听特定的端口号。若是使用特殊值0(零),则Tomcat将为链接器随机选择一个空闲的端口。这是一般只用在嵌入式和测试应用程序。
protocol
Sets the protocol to handle incoming traffic. The default value is HTTP/1.1 which uses an auto-switching mechanism to select either a blocking Java based connector or an APR/native based connector. If the PATH (Windows) or LD_LIBRARY_PATH (on most unix systems) environment variables contain the Tomcat native library, the APR/native connector will be used. If the native library cannot be found, the blocking Java based connector will be used. Note that the APR/native connector has different settings for HTTPS than the Java connectors.
To use an explicit protocol rather than rely on the auto-switching mechanism described above, the following values may be used:
org.apache.coyote.http11.Http11Protocol - blocking Java connector
org.apache.coyote.http11.Http11NioProtocol - non blocking Java connector
org.apache.coyote.http11.Http11AprProtocol - the APR/native connector.
Custom implementations may also be used.
Take a look at our Connector Comparison chart. The configuration for both Java connectors is identical, for http and https.
For more information on the APR connector and APR specific SSL settings please visit the APR documentation
设置协议来处理传入流量。默认值是 HTTP/1.1,将使用自动切换机制来选择阻塞的基于Java的链接器或APR /native 为基础的链接器。若是PATH(Windows)或LD_LIBRARY_PATH(在大多数Unix系统)的环境变量包含在Tomcat的本地库里,APR /native 链接器将被使用。若是在本地库中没法找到,阻断基于Java的链接器将被使用。须要注意的是使用HTTPS比Java链接器与APR /native 链接器有不一样的设置。一个明确的协议,而不是依靠上述自动切换机构,可用如下值: 指定模式
org.apache.coyote.http11.Http11Protocol -阻塞式的Java链接器
org.apache.coyote.http11.Http11NioProtocol -不阻塞Java链接器
org.apache.coyote.http11.Http11AprProtocol的 -的APR / native 链接器
也可使用的用户自定义的实现。看一看在咱们的链接器比较图。Java链接器,HTTP和HTTPS,配置是相同的。 APR链接器和APR特定的SSL设置的更多信息,请访问APR文档
proxyName
If this Connector is being used in a proxy configuration, configure this attribute to specify the server name to be returned for calls to request.getServerName(). See Proxy Support for more information.
若是这个链接正在使用的代理服务器配置,配置该属性指定的服务器的名称,能够调用request.getServerName()返回。有关更多信息,请参见代理支持。
proxyPort
If this Connector is being used in a proxy configuration, configure this attribute to specify the server port to be returned for calls to request.getServerPort(). See Proxy Support for more information.
若是这个链接正在使用的代理服务器配置,配置该属性指定服务器端口,能够调用request.getServerPort()返回。有关更多信息,请参见代理支持。
redirectPort
If this Connector is supporting non-SSL requests, and a request is received for which a matching<security-constraint> requires SSL transport, Catalina will automatically redirect the request to the port number specified here.
若是该链接器支持非SSL请求,而且接收到的请求为知足安全约束须要SSL传输, Catalina 将自动将请求重定向到指定的端口号。
scheme
Set this attribute to the name of the protocol you wish to have returned by calls torequest.getScheme(). For example, you would set this attribute to "https" for an SSL Connector. The default value is "http".
将该属性设置为你想调用request.getScheme()返回的协议的名称。例如,对于SSL链接器,你会将此属性设置为“HTTPS ”。默认值是“ HTTP ”。
secure
Set this attribute to true if you wish to have calls to request.isSecure() to return true for requests received by this Connector. You would want this on an SSL Connector or a non SSL connector that is receiving data from a SSL accelerator, like a crypto card, a SSL appliance or even a webserver. The default value is false.
若是你想调用request.isSecure()收到此链接器的请求返回true,请该该属性设置为true。您但愿SSL链接器或非SSL链接器接收数据经过一个SSL加速器,像加密卡,SSL设备,甚至一个web服务器。默认值是假的。
URIEncoding
This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, ISO-8859-1 will be used.
解决咱们的乱码问题
这将指定使用的字符编码,来解码URI字符。若是没有指定,ISO-8859-1将被使用。
useBodyEncodingForURI
This specifies if the encoding specified in contentType should be used for URI query parameters, instead of using the URIEncoding. This setting is present for compatibility with Tomcat 4.1.x, where the encoding specified in the contentType, or explicitly set using Request.setCharacterEncoding method was also used for the parameters from the URL. The default value is false.
这指定是否应该用于URI查询参数,而不是使用URIEncoding contentType中指定的编码。此设置兼容性Tomcat 4.1.x版(该版在contentType中指定编码,或者使用request.setCharacterEncoding的方法显式设置(参数为 URL传来的值)。默认值false。
useIPVHosts
Set this attribute to true to cause Tomcat to use the IP address that the request was received on to determine the Host to send the request to. The default value is false.
将该属性设置为true会致使Tomcat使用收到请求的IP地址,来肯定将请求发送到哪一个主机。默认值是假的。
xpoweredBy
Set this attribute to true to cause Tomcat to advertise support for the Servlet specification using the header recommended in the specification. The default value is false.
将此属性设置为true会致使Tomcat支持使用Servlet规范的通知,(在规范中推荐使用头字段)。默认值是假的。
标准实现(高亮的是重点)
除了上面列出的常见的链接器属性,标准的HTTP链接器(BIO,NIO和APR/native)都支持如下属性
Attribute
Description
acceptCount
The maximum queue length for incoming connection requests when all possible request processing threads are in use. Any requests received when the queue is full will be refused. The default value is 100.
当全部可能的请求处理线程都在使用时,传入链接请求的最大队列长度。当队列满时收到的任何请求将被拒绝。默认值是100。
acceptorThreadCount
The number of threads to be used to accept connections. Increase this value on a multi CPU machine, although you would never really need more than 2. Also, with a lot of non keep alive connections, you might want to increase this value as well. Default value is 1.
用于接受链接的线程的数量。在一个多CPU的机器上,增长该值,虽然你可能不会真正须要超过2个。此外,有不少非保持活动链接,您可能须要增长这个值。默认值是 1。
acceptorThreadPriority
The priority of the acceptor threads. The threads used to accept new connections. The default value is 5 (the value of the java.lang.Thread.NORM_PRIORITY constant). See the JavaDoc for the java.lang.Thread class for more details on what this priority means.
接收器线程的优先级。该线程用来接受新的链接。默认值是5(java.lang.Thread.NORM_PRIORITY常量)。更多这个优先级是什么意思的详细信息,请查看java.lang.Thread的类的JavaDoc 。
address
For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server.
对于拥有多个IP地址的服务器,该属性指定哪一个地址将被用于在指定端口上监听。默认状况下,该端口将被用于与服务器相关联的全部IP地址。
bindOnInit
Controls when the socket used by the connector is bound. By default it is bound when the connector is initiated and unbound when the connector is destroyed. If set to false, the socket will be bound when the connector is started and unbound when it is stopped.
控制链接器绑定时套接字的使用。缺省状况,当链接器被启动时套接字被绑定和当链接器被销毁时套接字解除绑定。若是设置为false,链接器启动时套接字被绑定,链接器中止时套接字解除绑定。
compressableMimeType
The value is a comma separated list of MIME types for which HTTP compression may be used. The default value is text/html,text/xml,text/plain.
该值是一个被用于HTTP压缩的逗号分隔的MIME类型列表。默认值是text / html类型,为text / xml,text / plain。
compression
The Connector may use HTTP/1.1 GZIP compression in an attempt to save server bandwidth. The acceptable values for the parameter is "off" (disable compression), "on" (allow compression, which causes text data to be compressed), "force" (forces compression in all cases), or a numerical integer value (which is equivalent to "on", but specifies the minimum amount of data before the output is compressed). If the content-length is not known and compression is set to "on" or more aggressive, the output will also be compressed. If not specified, this attribute is set to "off".
Note: There is a tradeoff between using compression (saving your bandwidth) and using the sendfile feature (saving your CPU cycles). If the connector supports the sendfile feature, e.g. the NIO connector, using sendfile will take precedence over compression. The symptoms will be that static files greater that 48 Kb will be sent uncompressed. You can turn off sendfile by setting useSendfile attribute of the connector, as documented below, or change the sendfile usage threshold in the configuration of the DefaultServlet in the defaultconf/web.xml or in the web.xml of your web application. 一般会在ngnix里面配置压缩
开启压缩GZIP js
为了节省服务器带宽,链接器可使用HTTP/1.1 GZIP压缩。可接受的参数的值是“off ”(禁用压缩),“on ”(容许压缩,这会致使文本数据被压缩),“force ”(强制在全部的状况下压缩),或者一个整数值(这是至关于为“on”,但指定了输出以前被压缩的数据最小量)。若是不知道内容长度但被设置为“on”或更积极的压缩,输出的数据也将被压缩。若是没有指定,该属性被设置为“关”。
注意:这是使用压缩(节省您的带宽)和使用sendfile功能(节省你的CPU周期)之间的权衡。若是链接器支持sendfile功能,例如NIO链接,则使用sendfile将优先于压缩。症状是48 KB的静态文件将未压缩就发送。你能够以下文所述经过设置链接器的useSendfile属性来关闭sendfile,或在默认的conf/web.xml或者你的web应用的web.xml中配置DefaultServlet来改变sendfile的使用量阈值。
compressionMinSize
If compression is set to "on" then this attribute may be used to specify the minimum amount of data before the output is compressed. If not specified, this attribute is defaults to "2048".
若是压缩被设置为“on”,那么该属性能够用于指定在输出以前被压缩的数据的最小量。若是未指定,此属性默认为“2048”。
connectionLinger
The number of seconds during which the sockets used by this Connector will linger when they are closed. The default value is -1 which disables socket linger.
链接器的套接字被关闭时的逗留秒数。若是没有指定,将使用默认的JVM。
connectionTimeout
The number of milliseconds this Connector will wait, after accepting a connection, for the request URI line to be presented. Use a value of -1 to indicate no (i.e. infinite) timeout. The default value is 60000 (i.e. 60 seconds) but note that the standard server.xml that ships with Tomcat sets this to 20000 (i.e. 20 seconds). UnlessdisableUploadTimeout is set to false, this timeout will also be used when reading the request body (if any).
在将提交的请求URI行呈现以后,链接器将等待接受链接的毫秒数。使用值-1表示没有超时(即无限)。默认值是60000(60秒),但请注意,Tomcat的标准server.xml中,设置为20000(即20秒)。
connectionUploadTimeout
Specifies the timeout, in milliseconds, to use while a data upload is in progress. This only takes effect if disableUploadTimeout is set to false.
上传数据过程当中,指定的以毫秒为单位超时时间。只有在设置disableUploadTimeout为false有效。
disableUploadTimeout
This flag allows the servlet container to use a different, usually longer connection timeout during data upload. If not specified, this attribute is set to true which disables this longer timeout.
此标志容许servlet容器在数据上传时使用不一样的链接超时,一般较长。若是没有指定,该属性被设置为true,禁用上传超时。
executor
A reference to the name in an Executor element. If this attribute is set, and the named executor exists, the connector will use the executor, and all the other thread attributes will be ignored. Note that if a shared executor is not specified for a connector then the connector will use a private, internal executor to provide the thread pool.
指向Executor元素的引用。若是这个属性被设置,而且被命名的executor存在,链接器将使用这个executor,而其余全部线程相关属性将被忽略。请注意共享的executor若是没有指定到一个链接器,则该链接器将使用一个私有的,内部的executor来提供线程池。
executorTerminationTimeoutMillis
The time that the private internal executor will wait for request processing threads to terminate before continuing with the process of stopping the connector. If not set, the default is 0 (zero) for the BIO connector and 5000 (5 seconds) for the NIO and APR/native connectors.
keepAliveTimeout
The number of milliseconds this Connector will wait for another HTTP request before closing the connection. The default value is to use the value that has been set for theconnectionTimeout attribute. Use a value of -1 to indicate no (i.e. infinite) timeout.
此链接器在关闭链接以前将等待另外一个HTTP请求的毫秒数。默认值是使用已设置的connectionTimeout属性的值。使用值-1表示没有超时(即无限)。
maxConnections
The maximum number of connections that the server will accept and process at any given time. When this number has been reached, the server will accept, but not process, one further connection. This additional connection be blocked until the number of connections being processed falls below maxConnections at which point the server will start accepting and processing new connections again. Note that once the limit has been reached, the operating system may still accept connections based on the acceptCount setting. The default value varies by connector type. For BIO the default is the value of maxThreads unless anExecutor is used in which case the default will be the value of maxThreads from the executor. For NIO the default is 10000. For APR/native, the default is 8192.
Note that for APR/native on Windows, the configured value will be reduced to the highest multiple of 1024 that is less than or equal to maxConnections. This is done for performance reasons.
If set to a value of -1, the maxConnections feature is disabled and connections are not counted.
在任何给定的时间服务器接受并处理的最大链接数。当这个数字已经达到了,服务器将不会接受任何链接,直到链接的数量降到低于此值。基于acceptCount的设置,操做系统可能仍然接受链接。默认值根据不一样的链接器类型而不一样。对于BIO,默认的是maxThreads的值,除非使用了Executor,在这种状况下默认值是executor的maxThreads值 。对于NIO的默认值是10000。APR /native的默认值是8192。
须要注意的是Windows系统的APR/native,所配置的值将减小到小于或等于maxConnections的1024的倍数的最大值。这样作是出于性能方面的考虑。
若是设置的值-1,maxConnections功能被禁用,并且链接数将不作计算。
maxExtensionSize
Limits the total length of chunk extensions in chunked HTTP requests. If the value is -1, no limit will be imposed. If not specified, the default value of 8192 will be used.
maxHttpHeaderSize
The maximum size of the request and response HTTP header, specified in bytes. If not specified, this attribute is set to 8192 (8 KB).
请求和响应的HTTP头的(以字节为单位的)最大尺寸。若是没有指定,该属性被设置为8192(8 KB)。
maxKeepAliveRequests
The maximum number of HTTP requests which can be pipelined until the connection is closed by the server. Setting this attribute to 1 will disable HTTP/1.0 keep-alive, as well as HTTP/1.1 keep-alive and pipelining. Setting this to -1 will allow an unlimited amount of pipelined or keep-alive HTTP requests. If not specified, this attribute is set to 100.
HTTP请求最大长链接个数。将此属性设置为1,将禁用HTTP/1.0、以及HTTP/1.1的长链接。设置为-1,不由用。若是没有指定,该属性被设置为100。
maxSwallowSize
The maximum number of request body bytes (excluding transfer encoding overhead) that will be swallowed by Tomcat for an aborted upload. An aborted upload is when Tomcat knows that the request body is going to be ignored but the client still sends it. If Tomcat does not swallow the body the client is unlikely to see the response. If not specified the default of 2097152 (2 megabytes) will be used. A value of less than zero indicates that no limit should be enforced.
maxThreads
The maximum number of request processing threads to be created by this Connector, which therefore determines the maximum number of simultaneous requests that can be handled. If not specified, this attribute is set to 200. If an executor is associated with this connector, this attribute is ignored as the connector will execute tasks using the executor rather than an internal thread pool.
最多同时处理的链接数,Tomcat使用线程来处理接收的每一个请求。这个值表示Tomcat可建立的最大的线程数。若是没有指定,该属性被设置为200。若是使用了execute将忽略此链接器的该属性,链接器将使用execute,而不是一个内部线程池来处理请求。
maxTrailerSize
Limits the total length of trailing headers in the last chunk of a chunked HTTP request. If the value is -1, no limit will be imposed. If not specified, the default value of 8192will be used.
限制一个分块的HTTP请求中的最后一个块的尾随标头的总长度。若是该值是-1,没有限制的被强加。若是没有指定,默认值是8192。
minSpareThreads
The minimum number of threads always kept running. If not specified, the default of 10 is used.
始终保持运行最小线程数。若是没有指定,则默认为10。
noCompressionUserAgents
The value is a regular expression (using java.util.regex) matching the user-agent header of HTTP clients for which compression should not be used, because these clients, although they do advertise support for the feature, have a broken implementation. The default value is an empty String (regexp matching disabled).
该值是一个正则表达式(使用java.util.regex),匹配不该该使用压缩的HTTP客户端的用户代理标头。由于这些客户端,虽然他们宣称支持压缩功能,但实现不完整。默认值是一个空字符串(正则表达式匹配禁用)。
processorCache
The protocol handler caches Processor objects to speed up performance. This setting dictates how many of these objects get cached. -1 means unlimited, default is 200. If not using Servlet 3.0 asynchronous processing, a good default is to use the same as the maxThreads setting. If using Servlet 3.0 asynchronous processing, a good default is to use the larger of maxThreads and the maximum number of expected concurrent requests (synchronous and asynchronous).
协议处理器缓存Processor对象以提升性能。此设置规定了这些对象有多少能获得缓存。-1意味着无限制,默认为200。若是不使用Servlet 3.0的异步处理,一个好的默认是使用maxThreads设置。若是使用Servlet 3.0的异步处理,一个好的默认是使用maxThreads和最大预期的并发请求(同步和异步)的最大值中的较大值。
restrictedUserAgents
The value is a regular expression (using java.util.regex) matching the user-agent header of HTTP clients for which HTTP/1.1 or HTTP/1.0 keep alive should not be used, even if the clients advertise support for these features. The default value is an empty String (regexp matching disabled).
该值是一个正则表达式(使用java.util.regex),匹配用户代理头的HTTP浏览器将不能使用HTTP/1.1或HTTP/1.0长链接,即便该浏览器宣称支持这些功能的。默认值是一个空字符串(正则表达式匹配禁用)。
server
Overrides the Server header for the http response. If set, the value for this attribute overrides the Tomcat default and any Server header set by a web application. If not set, any value specified by the application is used. If the application does not specify a value then Apache-Coyote/1.1 is used. Unless you are paranoid, you won't need this feature.
覆盖服务器的HTTP响应头。若是设置了这个属性的值将覆盖Web应用程序设置的Tomcat的默认头和任何服务器头。若是没有设置,应用程序指定的任何值将被使用。若是应用程序没有指定一个值,那么Apache-Coyote/1.1将被使用。除非你是偏执狂,你将再也不须要此功能。
socketBuffer
The size (in bytes) of the buffer to be provided for socket output buffering. -1 can be specified to disable the use of a buffer. By default, a buffers of 9000 bytes will be used.
为套接字输出缓冲而提供的缓冲区的大小(以字节为单位)。-1能够被指定来禁止使用的缓冲区。默认状况下,一个9000个字节的缓冲区将被使用。
SSLEnabled
Use this attribute to enable SSL traffic on a connector. To turn on SSL handshake/encryption/decryption on a connector set this value to true. The default value is false. When turning this value true you will want to set the scheme and the secureattributes as well to pass the correct request.getScheme() and request.isSecure() values to the servlets See SSL Support for more information.
在链接器上使用此属性来启用SSL加密传输。若是要打开SSL握手/加密/解密,请设置true。默认值是false。当设置这个值为true时,为了传递正确的request.getScheme()和 request.isSecure()到servlets,你须要设置scheme和secure属性。更多信息请查看SSL支持。
tcpNoDelay
If set to true, the TCP_NO_DELAY option will be set on the server socket, which improves performance under most circumstances. This is set to true by default.
若是设置为true,TCP_NO_DELAY选项将被设置在服务器上的套接字上,在大多数状况下,这样能够提升性能。默认设置为true。
threadPriority
The priority of the request processing threads within the JVM. The default value is 5(the value of the java.lang.Thread.NORM_PRIORITY constant). See the JavaDoc for thejava.lang.Thread class for more details on what this priority means.
在JVM中请求处理线程的优先级。默认值是5(java.lang.Thread.NORM_PRIORITY常量值)。关于优先级的更多详细信息,请查看java.lang.Thread的类的JavaDoc 。
upgradeAsyncWriteBufferSize
The default size of the buffer to allocate to for asynchronous writes that can not be completed in a single operation. Data that can't be written immediately will be stored in this buffer until it can be written. If more data needs to be stored than space is available in the buffer than the size of the buffer will be increased for the duration of the write. If not specified the default value of 8192 will be used.
最佳实践
4、禁用AJP链接器
AJP(Apache JServerProtocol)
AJPv13协议是面向包的。WEB服务器和Servlet容器经过TCP链接来交互;为了节省SOCKET建立的昂贵代价,WEB服务器会尝试维护一个永久TCP链接到servlet容器,而且在多个请求和响应周期过程会重用链接。
咱们通常是使用Nginx+tomcat的架构,因此用不着AJP协议,因此把AJP链接器禁用。
5、JVM调优(同垃圾回收
修改文件:bin/catalina.sh
JAVA_OPTS="-Dfile.encoding=UTF-8-server –Xms512m -Xmx1024m -XX:NewSize=512m -XX:MaxNewSize=512m -XX:PermSize=256m-XX:MaxPermSize=256m -XX:NewRatio=2 -XX:MaxTenuringThreshold=50-XX:+DisableExplicitGC"
参数说明:
一、 file.encoding 默认文件编码
二、 -Xmx1024m 设置JVM最大可用内存为1024MB
三、 -Xms1024m 设置JVM最小内存为1024m。此值能够设置与-Xmx相同,以免每次垃圾回收完成后JVM从新分配内存。
四、 -XX:NewSize 设置年轻代大小
五、 XX:MaxNewSize 设置最大的年轻代大小
六、 -XX:PermSize 设置永久代大小
七、 -XX:MaxPermSize 设置最大永久代大小
八、 -XX:NewRatio=4:设置年轻代(包括Eden和两个Survivor区)与终身代的比值(除去永久代)。设置为4,则年轻代与终身代所占比值为1:4,年轻代占整个堆栈的1/5
九、 -XX:MaxTenuringThreshold=0:设置垃圾最大年龄,默认为:15。若是设置为0的话,则年轻代对象不通过Survivor区,直接进入年老代。对于年老代比较多的应用,能够提升效率。若是将此值设置为一个较大值,则年轻代对象会在Survivor区进行屡次复制,这样能够增长对象再年轻代的存活时间,增长在年轻代即被回收的概论。
十、 -XX:+DisableExplicitGC这个将会忽略手动调用GC的代码使得System.gc()的调用就会变成一个空调用,彻底不会触发任何GC
)
贴一个网友调优后的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="8005" shutdown="SHUTDOWN"> <Listener className="org.apache.catalina.startup.VersionLoggerListener" /> <!-- 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="800" minSpareThreads="100" maxQueueSize="100" prestartminSpareThreads="true"/> <!-- 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 --> <!--maxPostSize参数形式处理的最大长度,若是没有指定,该属性被设置为2097152(2兆字节)。上传提交的时候能够用的 acceptCount请求的最大队列长度,当队列满时收到的任何请求将被拒绝 acceptorThreadCount 用于接受链接的线程的数量 disableUploadTimeout 禁用上传超时。 maxConnections 服务器接受并处理的最大链接数 SSLEnabled 在链接器上使用此属性来启用SSL加密传输 --> <Connector executor="tomcatThreadPool" port="8080" protocol="org.apache.coyote.http11.Http11NioProtocol" connectionTimeout="20000" redirectPort="8443" maxPostSize="10485760" acceptCount="100" acceptorThreadCount="2" disableUploadTimeout="true" maxConnections="10000" SSLEnabled="false" /> <!-- 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 BIO implementation that requires the JSSE style configuration. When using the APR/native implementation, the OpenSSL style configuration is required as described in the APR/native documentation --> <!-- <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol" maxThreads="150" SSLEnabled="true" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" /> --> <!-- Define an AJP 1.3 Connector on port 8009 --> <Connector port="8009" protocol="AJP/1.3" 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"> <!--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"/> --> <!-- 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"> <!-- 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 "%r" %s %b" /> </Host> </Engine> </Service></Server>