天天看點

tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化

1.  目的

通過優化tomcat提高網站的并發能力。當我們今天我們将這個優化講完之前  優化完成後看能達到什麼層次。

2.  伺服器資源

伺服器所能提供CPU、記憶體、硬碟的性能對處理能力有決定性影響。硬體我們不說了 這個方面是錢越多越好是吧。

3.  優化配置

3.1. 配置tomcat管理者賬戶

在conf/ tomcat-users.xml下添加使用者:

<role rolename="manager"/>

<rolerolename="manager-gui"/>

<role rolename="admin"/>

<rolerolename="admin-gui"/>

<user username="tomcat"password="tomcat"roles="admin-gui,admin,manager-gui,manager"/>

啟動tomcat,登入檢視資訊:

http://127.0.0.1:8080/

tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化

ajp-伺服器之間的通信協定,socket層  然後組裝一定的資料給對方 資料形式也可能json  xml 文本 隻是各個廠家約定的,例如我們在一個實體主機跑三個TOMCAT伺服器的時候是吧,這個負載均衡  通過權數和算法

3.2. tomcat的3種運作模式

tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化

tomcat的運作模式有3種:

tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化

1、  bio

預設的模式,性能非常低下,沒有經過任何優化處理和支援. 一個線程處理一個請求。缺點:并發量高時,線程數較多,浪費資源。

Tomcat7或以下,在Linux系統中預設使用這種方式。

2、  nio

nio(new I/O),是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"/>

3、  apr

安裝起來最困難,但是從作業系統級别來解決異步的IO問題,大幅度的提高性能.

即Apache PortableRuntime,從作業系統層面解決io阻塞問題。

Tomcat7或Tomcat8在Win7或以上的系統中啟動預設使用這種方式。

Linux如果安裝了apr和native,Tomcat直接啟動就支援apr。

具體安裝辦法 參見這個位址:https://my.oschina.net/lsw90/blog/181161

4、  在那裡看我們的tomcat以何種工作模式啟動的啊?

Tomcat啟動的時候,可以通過log看到Connector使用的是哪一種運作模式:

StartingProtocolHandler ["http-bio-8080"]

StartingProtocolHandler ["http-nio-8080"]

StartingProtocolHandler ["http-apr-8080"]

tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化

3.2.1.  啟動NIO模式

修改server.xml裡的Connector節點,修改protocol為org.apache.coyote.http11.Http11NioProtocol

tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化

  這裡有個問題啊? 為什麼它不直接改成NIO的形式呢?

       這個方式是利用了jdk 1.4及後續版本提供的一種新的I/O操作方式(即java.nio包及其子包)為橋梁實作的,不改成這種優化方式就是為了相容1.4之前的JAVA項目也能跑起來。

tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化

3.3. 執行器(線程池)

預設的tomcat沒有啟用線程池,

在tomcat中每一個使用者請求都是一個線程,是以可以使用線程池提高性能。這裡前台其實有一個排程線程,然後排程線程會放入線程池内,然後到到一定的時候線程池的任務變成工作線程啊。

3.3.1.  開啟并且使用

配置:

tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化

3.3.2.  參數說明

http://127.0.0.1:8088/docs/config/http.html

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.3.3.  最佳實踐

tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化

3.4.連接配接器(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

3.4.1.  通用屬性(高亮的是重點)

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 to

request.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規範的通知,(在規範中推薦使用頭字段)。預設值是假的。

3.4.2.  标準實作(高亮的是重點)

除了上面列出的常見的連接配接器屬性,标準的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 default

conf/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   (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 

8192

will 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 

secure

attributes 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 the

java.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.

3.4.3.   NIO的具體配置

Attribute Description
pollerThreadCount

(int)The number of threads to be used to run for the polling events. Default value is 1 per processor up to and including version 7.0.27. Default value as of version 7.0.28 is 1 per processor but not more than 2.

When accepting a socket, the operating system holds a global lock. So the benefit of going above 2 threads diminishes rapidly. Having more than one thread is for system that need to accept connections very rapidly. However usually just increasing acceptCount will solve that problem. Increasing this value may also be beneficial when a large amount of send file operations are going on.

(int)用來處理輪詢事件的線程的數量。在版本7.0.27及以前版本,預設值是每個處理器1個。版本7.0.28的預設值是每個處理器1個,但不超過2個。

當接受一個套接字,作業系統擁有全局的鎖。是以超過2個線程的好處而迅速減小。有一個以上的線程是因為系統需要非常迅速地接受連接配接。但通常隻要增加acceptCount值就可以解決這個問題。增加該值也可能是有用的,當大量發送檔案操作發生的時候。

pollerThreadPriority

(int)The priority of the poller threads. The default value is 5 (the value of thejava.lang.Thread.NORM_PRIORITY constant). See the JavaDoc for the java.lang.Thread class for more details on what this priority means.

(int)輪詢線程的優先級。預設值是5(java.lang.Thread.NORM_PRIORITY常量值)。優先級的更多詳細資訊,可以查考java.lang.Thread類的JavaDoc 。

selectorTimeout

(int)The time in milliseconds to timeout on a select() for the poller. This value is important, since connection clean up is done on the same thread, so do not set this value to an extremely high one. The default value is 1000 milliseconds.

(int)選擇輪詢器select()的逾時時間(以毫秒為機關)。這個值非常重要,因為連接配接清理工作也是在同一個線程裡的,是以不要将此值設定為一個非常高的。預設值是1000毫秒。

useComet

(bool)Whether to allow comet servlets or not. Default value is true.

(bool)是否允許Comet servlet。預設值是 true。

useSendfile

(bool)Use this attribute to enable or disable sendfile capability. The default value istrue.

(bool)使用此屬性來啟用或禁用sendfile的能力。預設值是true。

socket.directBuffer

(bool)Boolean value, whether to use direct ByteBuffers or java mapped ByteBuffers. Default is false.

When you are using direct buffers, make sure you allocate the appropriate amount of memory for the direct memory space. On Sun's JDK that would be something like -XX:MaxDirectMemorySize=256m.

(bool)選擇使​​用直接ByteBuffers或Java映射的ByteBuffers。預設是false。

當您使用直接ByteBuffers,請確定你配置設定适當的記憶體量給直接記憶體空間。在Sun的JDK中,配置如-XX:MaxDirectMemorySize = 256M。

socket.appReadBufSize

(int)Each connection that is opened up in Tomcat get associated with a read ByteBuffer. This attribute controls the size of this buffer. By default this read buffer is sized at8192 bytes. For lower concurrency, you can increase this to buffer more data. For an extreme amount of keep alive connections, decrease this number or increase your heap size.

(int)在Tomcat中每個連接配接的開辟連接配接一個讀ByteBuffer。此屬性控制這個緩沖區的大小。預設情況下,這個讀緩沖區大小為8192位元組。對于較低的并發,你可以增加這個值以緩沖更多的資料。對于長連接配接數很多的情況,你需要降低這個數值或者增加堆大小。

socket.appWriteBufSize

(int)Each connection that is opened up in Tomcat get associated with a write ByteBuffer. This attribute controls the size of this buffer. By default this write buffer is sized at8192 bytes. For low concurrency you can increase this to buffer more response data. For an extreme amount of keep alive connections, decrease this number or increase your heap size.

The default value here is pretty low, you should up it if you are not dealing with tens of thousands concurrent connections.

(int)在Tomcat中每個連接配接的開辟連接配接一個寫ByteBuffer。此屬性控制這個緩沖區的大小。預設情況下,這個寫緩沖區大小為8192位元組。對于較低的并發,你可以增加這個值以緩沖更多的響應資料。對于長連接配接數很多的情況,你需要降低這個數值或者增加堆大小。

這裡的預設值是相當低的,如果面對的不是幾萬并發連接配接,你應該增大該值。

socket.bufferPool

(int)The NIO connector uses a class called NioChannel that holds elements linked to a socket. To reduce garbage collection, the NIO connector caches these channel objects. This value specifies the size of this cache. The default value is 500, and represents that the cache will hold 500 NioChannel objects. Other values are -1 for unlimited cache and 0 for no cache.

(int)NIO連接配接器使用NioChannel這個類來持有連結到一個套接字的元素。為了減少垃圾收集,NIO連接配接器緩存這些通道的對象。此值指定這個緩存的大小。預設值是500,表示緩存将持有500個 NioChannel的對象。-1表示不限制緩存大小,0表示不緩存。

socket.bufferPoolSize

(int)The NioChannel pool can also be size based, not used object based. The size is calculated as follows:

NioChannel buffer size = read buffer size + write buffer size

SecureNioChannel buffer size = application read buffer size + application write buffer size + network read buffer size + network write buffer size

The value is in bytes, the default value is 1024*1024*100 (100MB).

(int)NioChannel池,也可以是基于尺寸大小,而不是基于對象數的。該大小的計算如下:

NioChannel的緩沖區大小=讀取緩沖區大小+寫入緩沖區大小

SecureNioChannel的緩沖區大小=應用程式讀取緩沖區大小+應用程式寫入緩沖區的大小+網絡讀取緩沖區大小+網絡寫入緩沖區的大小

值(以位元組為機關),預設值1024 * 1024 * 100 (100MB)。

socket.processorCache

(int)Tomcat will cache SocketProcessor objects to reduce garbage collection. The integer value specifies how many objects to keep in the cache at most. The default is 500. Other values are -1 for unlimited cache and 0 for no cache.

(int)以減少垃圾收集,Tomcat緩存SocketProcessor對象。該值指定保持在緩存中最多有多少個對象。預設值是500。-1表示不限制緩存大小,0表示不緩存。

socket.keyCache

(int)Tomcat will cache KeyAttachment objects to reduce garbage collection. The integer value specifies how many objects to keep in the cache at most. The default is 500. Other values are -1 for unlimited cache and 0 for no cache.

(int)以減少垃圾收集,Tomcat緩存KeyAttachment對象。該值指定保持在緩存中最多有多少個對象。預設值是500。-1表示不限制緩存大小,0表示不緩存。

socket.eventCache

(int)Tomcat will cache PollerEvent objects to reduce garbage collection. The integer value specifies how many objects to keep in the cache at most. The default is 500. Other values are -1 for unlimited cache and 0 for no cache.

(int)以減少垃圾收集,Tomcat緩存PollerEvent對象。該值指定保持在緩存中最多有多少個對象。預設值是500。-1表示不限制緩存大小,0表示不緩存。

selectorPool.maxSelectors

(int)The max selectors to be used in the pool, to reduce selector contention. Use this option when the command line org.apache.tomcat.util.net.NioSelectorShared value is set to false. Default value is 200.

(int)以減少選擇器的争用,在池中使用的選擇器最大個數。指令行org.apache.tomcat.util.net.NioSelectorShared值設定為false時,使用此選項。預設值是200。

selectorPool.maxSpareSelectors

(int)The max spare selectors to be used in the pool, to reduce selector contention. When a selector is returned to the pool, the system can decide to keep it or let it be GC'd. Use this option when the command line org.apache.tomcat.util.net.NioSelectorShared value is set to false. Default value is -1 (unlimited).

(int)以減少選擇器的争用,在池中使用的最大備用選擇器個數。當選擇器傳回到池中時,系統可以決定保留它或者讓他垃圾回收。當org.apache.tomcat.util.net.NioSelectorShared 值設定為false時,使用此選項。預設值是-1(無限制)。

command-line-options

The following command line options are available for the NIO connector:

-Dorg.apache.tomcat.util.net.NioSelectorShared=true|false - default is true. Set this value to false if you wish to use a selector for each thread. When you set it to false, you can control the size of the pool of selectors by using the selectorPool.maxSelectors attribute.

下面的指令行選項可用于NIO連接配接器:-Dorg.apache.tomcat.util.net.NioSelectorShared=true|false

 預設情況下是true。如果你想每個線程使用一個選擇器,将此值設定為false。當你将它設定為false,你可以通過使用selectorPool.maxSelectors屬性控制選擇器池的大小。

oomParachute

(int)The NIO connector implements an OutOfMemoryError strategy called parachute. It holds a chunk of data as a byte array. In case of an OOM, this chunk of data is released and the error is reported. This will give the VM enough room to clean up. The oomParachute represents the size in bytes of the parachute(the byte array). The default value is 1024*1024(1MB). Please note, this only works for OOM errors regarding the Java Heap space, and there is absolutely no guarantee that you will be able to recover at all. If you have an OOM outside of the Java Heap, then this parachute trick will not help.

(int)NIO連接配接器實作了一個名叫parachute的OutOfMemoryError錯誤的政策。它擁有一個塊的資料作為一個位元組數組。在一個OOM的情況下,這個資料塊被釋放,并報告錯誤。這會給VM足夠的空間來清理。oomParachute代表parachute(位元組數組)的大小(以位元組為機關)。預設值是 1024 * 1024(1MB)。請注意,這僅适用于關于Java堆空間的OOM錯誤,也不是絕對保證,你将能夠恢複所有。如果你有一個Java堆之外OOM的,那麼這個parachute也無濟于事。

3.4.4.  最佳實踐

tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化

4.  禁用AJP連接配接器

AJP(Apache JServerProtocol)

AJPv13協定是面向包的。WEB伺服器和Servlet容器通過TCP連接配接來互動;為了節省SOCKET建立的昂貴代價,WEB伺服器會嘗試維護一個永久TCP連接配接到servlet容器,并且在多個請求和響應周期過程會重用連接配接。

tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化

我們一般是使用Nginx+tomcat的架構,是以用不着AJP協定,是以把AJP連接配接器禁用。

tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化

在管理界面中看不到ajp了:

tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化

5.  JVM參數的優化

因為Tomcat運作在JAVA虛拟機之上啊

适當調整Tomcat的運作JVM參數可以提升整體性能。

5.1. JVM記憶體模型

5.1.1.  Java棧

Java棧是與每一個線程關聯的,JVM在建立每一個線程的時候,會配置設定一定的棧空間給線程。它主要用來存儲線程執行過程中的局部變量,方法的傳回值,以及方法調用上下文。棧空間随着線程的終止而釋放。

5.1.2.  Java堆

Java中堆是由所有的線程共享的一塊記憶體區域,堆用來儲存各種JAVA對象,比如數組,線程對象等。

5.1.3.  Java堆的分區

JVM堆一般又可以分為以下三部分:

tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化

◆ Young 年輕區(代)

Young區被劃分為三部分,Eden區和兩個大小嚴格相同的Survivor區,其中,Survivor區間中,某一時刻隻有其中一個是被使用的,另外一個留做垃圾收集時複制對象用,在Eden區間變滿的時候, GC就會将存活的對象移到空閑的Survivor區間中,根據JVM的政策,在經過幾次垃圾收集後,任然存活于Survivor的對象将被移動到Tenured區間。

◆ Tenured 年老區

Tenured區主要儲存生命周期長的對象,一般是一些老的對象,當一些對象在Young複制轉移一定的次數以後,對象就會被轉移到Tenured區,一般如果系統中用了application級别(spring容器放在application)的緩存,緩存中的對象往往會被轉移到這一區間。

◆ Perm 永久區

Perm代主要儲存class,method,filed對象,這個區域不會被gc回收。這部份的空間一般不會溢出,除非一次性加載了很多的類,不過在涉及到熱部署的應用伺服器的時候,有時候會遇到java.lang.OutOfMemoryError : PermGen space 的錯誤,造成這個錯誤的很大原因就有可能是每次都重新部署,但是重新部署後,類的class沒有被解除安裝掉,這樣就造成了大量的class對象儲存在了perm中,這種情況下,一般重新啟動應用伺服器可以解決問題。

 tomcat熱部署:是指在你修改項目BUG的時候對JSP或JAVA類進行了修改在不重新開機WEB伺服器前提下能讓修改生效。但是對配置檔案的修改除外! 

Virtual區:虛拟區

最大記憶體和初始記憶體的內插補點,就是Virtual區。

5.1.4.  設定區大小

JVM提供了相應的參數來對記憶體大小進行配置。正如上面描述,JVM中堆被分為了3個大的區間,同時JVM也提供了一些選項對Young,Tenured的大小進行控制。

如何設定年輕代大小?哪些應用系統需要調整年輕代老年代  永久代?

 這個需要根據應用場景的特點設定啊,如果說我們需要經常建立對象啊  而且對象使用完後馬上會被回收的,這種場景年輕代可以适當調大。

  比如說:對外提供一個查詢資料的接口,傳回資料  查詢出來的對象轉換成json對象  然後這個接口頻繁通路  的我們可以适當調大一點。

 老年代:  靜态變量什麼的

tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化

◆ Total Heap

-Xms :指定了JVM初始啟動以後初始化記憶體

-Xmx:指定JVM堆得最大記憶體,在JVM啟動以後,會配置設定-Xmx參數指定大小的記憶體給JVM,但是不一定全部使用,JVM會根據-Xms參數來調節真正用于JVM的記憶體

-Xmx -Xms之差就是三個Virtual空間的大小

◆ Young Generation

-XX:NewRatio=8意味着tenured 和 young的比值8:1,這樣eden+2*survivor=1/9

堆記憶體

-XX:SurvivorRatio=32意味着eden和一個survivor的比值是32:1,這樣一個Survivor就占Young區的1/34.

-Xmn 參數設定了年輕代的大小

◆ Perm Generation

-XX:PermSize=16M -XX:MaxPermSize=64M

Thread Stack

-XX:Xss=128K

5.2. 常用參數

修改檔案: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"

參數說明:

1、  file.encoding 預設檔案編碼

2、  -Xmx1024m  設定JVM最大可用記憶體為1024MB

3、  -Xms1024m  設定JVM最小記憶體為1024m。此值可以設定與-Xmx相同,以避免每次垃圾回收完成後JVM重新配置設定記憶體。

4、  -XX:NewSize  設定年輕代大小

5、  XX:MaxNewSize 設定最大的年輕代大小

6、  -XX:PermSize  設定永久代大小

7、  -XX:MaxPermSize 設定最大永久代大小

8、  -XX:NewRatio=4:設定年輕代(包括Eden和兩個Survivor區)與終身代的比值(除去永久代)。設定為4,則年輕代與終身代所占比值為1:4,年輕代占整個堆棧的1/5

9、  -XX:MaxTenuringThreshold=0:設定垃圾最大年齡,預設為:15。如果設定為0的話,則年輕代對象不經過Survivor區,直接進入年老代。對于年老代比較多的應用,可以提高效率。如果将此值設定為一個較大值,則年輕代對象會在Survivor區進行多次複制,這樣可以增加對象再年輕代的存活時間,增加在年輕代即被回收的概論。

10、             -XX:+DisableExplicitGC這個将會忽略手動調用GC的代碼使得System.gc()的調用就會變成一個空調用,完全不會觸發任何GC

5.3. 在tomcat中設定JVM參數

5.3.1.  windows

修改bin/catalina.bat檔案設定參數(第一行 93行)

set JAVA_OPTS=-Dfile.encoding=UTF-8 -server-Xms1024m -Xmx2048m -XX:NewSize=512m -XX:MaxNewSize=1024m -XX:PermSize=256m-XX:MaxPermSize=256m -XX:MaxTenuringThreshold=10 -XX:NewRatio=2-XX:+DisableExplicitGC

tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化

5.3.2.  linux

修改bin/catalina.sh檔案參數(第一行)

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

tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化
tomcat7 性能優化,提高并發 1.  目的 2.  伺服器資源 3.  優化配置 4.  禁用AJP連接配接器 5.  JVM參數的優化

貼一個我最終的serverxml:

<?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>
           

繼續閱讀