• Tomcat配置及性能调优(转)


    本文链接:https://blog.csdn.net/zs742946530/article/details/82346707

    性能调优听起来很高大上,上规模的公司都有专业运维,一般这种事情也是由运维来做。不过作为程序猿我们也要了解其中的参数和设置。

       tomcat性能调优我们应该做哪些工作呢?

       首先我们找到tomcat文件目录下的conf文件夹下的server.xml文件。

      可以从如下几个方面去做工作:

    一、Tomcat的运行模式优化
    tomcat的运行模式有三种:1 、BIO     2  、 NIO     3  、APR

    不过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

    首先我们先来了解一下这三种模式的区别:

    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"]

    二、线程池优化
    默认的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 ,设置为负则不重建


    三、连接器(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.

    最佳实践
     

    四、禁用AJP连接器
    AJP(Apache JServerProtocol)

    AJPv13协议是面向包的。WEB服务器和Servlet容器通过TCP连接来交互;为了节省SOCKET创建的昂贵代价,WEB服务器会尝试维护一个永久TCP连接到servlet容器,并且在多个请求和响应周期过程会重用连接。

    我们一般是使用Nginx+tomcat的架构,所以用不着AJP协议,所以把AJP连接器禁用。

    五、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"

    参数说明:

    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

    贴一个网友调优后的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>

  • 相关阅读:
    LOJ #3219. 「PA 2019」Iloczyny Fibonacciego (斐波拉契表示性质+FFT)
    一类区间修改问题的做法
    [百炼智能]hihoCoder挑战赛37 D Items(树状数组维护01背包—梦想成真!!!)
    LOJ #2092. 「ZJOI2016」大森林(lct)
    LOJ #3220. 「PA 2019」Terytoria(随机染色或线段树)
    Codeforces 223E. Planar Graph(平面图)
    JZOJ 6678. 【2020.05.01省选模拟】苏菲的世界 (simpson积分+几何法求多个圆的并的面积)
    Day3-Python基础3---函数介绍
    Day2-Python基础2---字符编码与转码
    Day2-Python基础2---集合和文件操作
  • 原文地址:https://www.cnblogs.com/shmily2018/p/11590122.html
Copyright © 2020-2023  润新知