Tomcat配置及性能調優(轉)

本文連接: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>

相關文章
相關標籤/搜索