嵌入式Tomcat容器的参数(maxParameterCount&maxPostSize)设定,参数过多解决方案
官网的文档(tomcat doc)里如下maxParameterCountThe maximum number of parameter and value pairs (GET plus POST) which will be automatically parsed by the container. Parameter and value pairs beyond this li...
官网的文档(tomcat doc)里如下
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 filter can be used to reject requests that hit the limit. |
| 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 zero. If not specified, this attribute is set to 2097152 (2 megabytes). Note that the FailedRequestFilter can be used to reject requests that exceed this limit. |
简说
maxParameterCount 是
tomcat容器来限定你 单次请求的参数的最大数量,默认是10000。所以通过这个属性你可以根据情况给设定适当的值。当然也有超出1w的情况怎么办?
上面文档里也有给出答案 小于0的设定可以禁用此制限。这也是很多网上资料设置-1的原因。
maxPostSize 是http-post单次请求内容或者说数据的最大限制,默认值为2M。同样小于0的设定可以禁用此制限
具体使用
tomcat/conf/server.xml文件中找到如下节点
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
(这里有好几个connector看自己用的是哪个端口的)
修改后
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" maxPostSize="-1" maxParameterCount="-1"/>
这是通常的做法,但有时如果tomcat容器内置的话你可能都找不到server.xml文件,
比如spring boo项目内置tomcat
这时候通常会想到 可以配置在application.properties里
然后翻一下看看application.properties里怎么配置
从spring-boot的doc看到只看到如下
server.tomcat.max-http-post-size=0 # Maximum size in bytes of the HTTP post content. |
没有找到关于maxParameterCount信息
在java类里的方法
@Bean public EmbeddedServletContainerFactory mbeddedServletContainerFactory() { TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory = new TomcatEmbeddedServletContainerFactory(); tomcatEmbeddedServletContainerFactory.addConnectorCustomizers(connector ->{ connector.setMaxPostSize(2); System.out.println("connector.getMaxPostSize: "+connector.getMaxPostSize()); System.out.println("connector.getPort: "+connector.getPort()); }); return tomcatEmbeddedServletContainerFactory; }
EmbeddedServletContainerCustomizer
这是一个自定义内置容器的接口,通过实现它可以创建内置容器
然后还找到已经实现了它类,
AbstractEmbeddedServletContainerFactory,
JettyEmbeddedServletContainerFactory,
TomcatEmbeddedServletContainerFactory,
UndertowEmbeddedServletContainerFactory
这里看到了定制tomcat容器的工厂类
这里就是我们这次用到的函数了为什么标记两个因为上边那个也可用,下面是官网给的说明
官网DOC选摘
Attributes
Common Attributes
All implementations of Connector support the following attributes:
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. |
asyncTimeout | The default timeout for asynchronous requests in milliseconds. If not specified, this attribute is set to the Servlet specification default of 30000 (30 seconds). |
enableLookups | Set to |
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. |
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 |
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 zero. If not specified, this attribute is set to 2097152 (2 megabytes). Note that the |
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). |
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 |
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. |
protocol | Sets the protocol to handle incoming traffic. The default value is |
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 |
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 |
redirectPort | If this Connector is supporting non-SSL requests, and a request is received for which a matching |
scheme | Set this attribute to the name of the protocol you wish to have returned by calls to |
secure | Set this attribute to |
URIEncoding | This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, UTF-8 will be used unless the |
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 Notes: 1) This setting is applied only to the query string of a request. Unlike |
useIPVHosts | Set this attribute to |
xpoweredBy | Set this attribute to |
Standard Implementation
The standard HTTP connectors (BIO, NIO, NIO2 and APR/native) all support the following attributes in addition to the common Connector attributes listed above.
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. |
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 |
acceptorThreadPriority | The priority of the acceptor threads. The threads used to accept new connections. The default value is |
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. |
allowHostHeaderMismatch | By default Tomcat will allow requests that specify a host in the request line but specify a different host in the host header. This check can be enabled by setting this attribute to |
allowedTrailerHeaders | By default Tomcat will ignore all trailer headers when processing chunked input. For a header to be processed, it must be added to this comma-separated list of header names. |
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 |
compressibleMimeType | The value is a comma separated list of MIME types for which HTTP compression may be used. The default value is |
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 |
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". |
connectionLinger | The number of seconds during which the sockets used by this Connector will linger when they are closed. The default value is |
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). Unless disableUploadTimeout is set to |
connectionUploadTimeout | Specifies the timeout, in milliseconds, to use while a data upload is in progress. This only takes effect if disableUploadTimeout is set to |
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 |
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. |
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 |
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 the connectionTimeout attribute. Use a value of -1 to indicate no (i.e. infinite) timeout. |
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 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. |
maxCookieCount | The maximum number of cookies that are permitted for a request. A value of less than zero means no limit. If not specified, a default value of 200 will be used. |
maxExtensionSize | Limits the total length of chunk extensions in chunked HTTP requests. If the value is |
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). |
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. |
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. Note that if an executor is configured any value set for this attribute will be recorded correctly but it will be reported (e.g. via JMX) as |
maxTrailerSize | Limits the total length of trailing headers in the last chunk of a chunked HTTP request. If the value is |
minSpareThreads | The minimum number of threads always kept running. This includes both active and idle threads. If not specified, the default of |
noCompressionUserAgents | The value is a regular expression (using |
processorCache | The protocol handler caches Processor objects to speed up performance. This setting dictates how many of these objects get cached. |
rejectIllegalHeaderName | If an HTTP request is received that contains an illegal header name (i.e. the header name is not a token) this setting determines if the request will be rejected with a 400 response ( |
relaxedPathChars | The HTTP/1.1 specification requires that certain characters are %nn encoded when used in URI paths. Unfortunately, many user agents including all the major browsers are not compliant with this specification and use these characters in unencoded form. To prevent Tomcat rejecting such requests, this attribute may be used to specify the additional characters to allow. If not specified, no addtional characters will be allowed. The value may be any combination of the following characters: |
relaxedQueryChars | The HTTP/1.1 specification requires that certain characters are %nn encoded when used in URI query strings. Unfortunately, many user agents including all the major browsers are not compliant with this specification and use these characters in unencoded form. To prevent Tomcat rejecting such requests, this attribute may be used to specify the additional characters to allow. If not specified, no addtional characters will be allowed. The value may be any combination of the following characters: |
restrictedUserAgents | The value is a regular expression (using |
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 |
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. |
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 |
tcpNoDelay | If set to |
threadPriority | The priority of the request processing threads within the JVM. The default value is |
upgradeAsyncWriteBufferSize | The default size of the buffer to allocate to for asynchronous writes that can not be completed in a single operation, specified in bytes. 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. |
Java TCP socket attributes
The BIO, NIO and NIO2 implementation support the following Java TCP socket attributes in addition to the common Connector and HTTP attributes listed above.
Attribute | Description |
---|---|
socket.rxBufSize | (int)The socket receive buffer (SO_RCVBUF) size in bytes. JVM default used if not set. |
socket.txBufSize | (int)The socket send buffer (SO_SNDBUF) size in bytes. JVM default used if not set. |
socket.tcpNoDelay | (bool)This is equivalent to standard attribute tcpNoDelay. |
socket.soKeepAlive | (bool)Boolean value for the socket's keep alive setting (SO_KEEPALIVE). JVM default used if not set. |
socket.ooBInline | (bool)Boolean value for the socket OOBINLINE setting. JVM default used if not set. |
socket.soReuseAddress | (bool)Boolean value for the sockets reuse address option (SO_REUSEADDR). JVM default used if not set. |
socket.soLingerOn | (bool)Boolean value for the sockets so linger option (SO_LINGER). A value for the standard attribute connectionLinger that is >=0 is equivalent to setting this to |
socket.soLingerTime | (int)Value in seconds for the sockets so linger option (SO_LINGER). This is equivalent to standard attribute connectionLinger. Both this attribute and |
socket.soTimeout | This is equivalent to standard attribute connectionTimeout. |
socket.performanceConnectionTime | (int)The first value for the performance settings. See Socket Performance Options. All three performance attributes must be set else the JVM defaults will be used for all three. |
socket.performanceLatency | (int)The second value for the performance settings. See Socket Performance Options. All three performance attributes must be set else the JVM defaults will be used for all three. |
socket.performanceBandwidth | (int)The third value for the performance settings. See Socket Performance Options. All three performance attributes must be set else the JVM defaults will be used for all three. |
socket.unlockTimeout | (int) The timeout for a socket unlock. When a connector is stopped, it will try to release the acceptor thread by opening a connector to itself. The default value is |
BIO specific configuration
The following attributes are specific to the BIO connector.
Attribute | Description |
---|---|
disableKeepAlivePercentage | The percentage of processing threads that have to be in use before HTTP keep-alives are disabled to improve scalability. Values less than |
NIO specific configuration
The following attributes are specific to the NIO connector.
Attribute | Description |
---|---|
pollerThreadCount | (int)The number of threads to be used to run for the polling events. Default value is |
pollerThreadPriority | (int)The priority of the poller threads. The default value is |
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 |
useComet | (bool)Whether to allow comet servlets or not. Default value is |
useSendfile | (bool)Use this attribute to enable or disable sendfile capability. The default value is |
socket.directBuffer | (bool)Boolean value, whether to use direct ByteBuffers or java mapped ByteBuffers. If |
socket.directSslBuffer | (bool)Boolean value, whether to use direct ByteBuffers or java mapped ByteBuffers for the SSL buffers. If |
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 at |
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 at |
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 |
socket.bufferPoolSize | (int)The NioChannel pool can also be size based, not used object based. The size is calculated as follows: |
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 |
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 |
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 |
selectorPool.maxSelectors | (int)The max selectors to be used in the pool, to reduce selector contention. Use this option when the command line |
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 |
command-line-options | The following command line options are available for the NIO connector: |
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 |
NIO2 specific configuration
The following attributes are specific to the NIO2 connector.
Attribute | Description |
---|---|
useCaches | (bool)Use this attribute to enable or disable object caching to reduce the amount of GC objects produced. The default value is |
useComet | (bool)Whether to allow comet servlets or not. Default value is |
useSendfile | (bool)Use this attribute to enable or disable sendfile capability. The default value is |
socket.directBuffer | (bool)Boolean value, whether to use direct ByteBuffers or java mapped ByteBuffers. If |
socket.directSslBuffer | (bool)Boolean value, whether to use direct ByteBuffers or java mapped ByteBuffers for the SSL buffers. If |
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 at |
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 at |
socket.bufferPoolSize | (int)The NIO2 connector uses a class called Nio2Channel that holds elements linked to a socket. To reduce garbage collection, the NIO2 connector caches these channel objects. This value specifies the size of this cache. The default value is |
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 |
socket.socketWrapperCache | (int)Tomcat will cache SocketWrapper objects to reduce garbage collection. The integer value specifies how many objects to keep in the cache at most. The default is |
oomParachute | (int)The NIO2 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 |
APR/native specific configuration
The following attributes are specific to the APR/native connector.
Attribute | Description |
---|---|
deferAccept | Sets the |
pollerSize | Amount of sockets that the poller responsible for polling kept alive connections can hold at a given time. Extra connections will be closed right away. The default value is 8192, corresponding to 8192 keep-alive connections. This is a synonym for maxConnections. |
pollerThreadCount | Number of threads used to poll kept alive connections. On Windows the default is chosen so that the sockets managed by each thread is less than 1024. For Linux the default is 1. Changing the default on Windows is likely to have a negative performance impact. |
pollTime | Duration of a poll call in microseconds. Lowering this value will slightly decrease latency of connections being kept alive in some cases, but will use more CPU as more poll calls are being made. The default value is 2000 (2ms). |
sendfileSize | Amount of sockets that the poller responsible for sending static files asynchronously can hold at a given time. Extra connections will be closed right away without any data being sent (resulting in a zero length file on the client side). Note that in most cases, sendfile is a call that will return right away (being taken care of "synchronously" by the kernel), and the sendfile poller will not be used, so the amount of static files which can be sent concurrently is much larger than the specified amount. The default value is 1024. |
sendfileThreadCount | Number of threads used service sendfile sockets. On Windows the default is chosen so that the sockets managed by each thread is less than 1024. For Linux the default is 1. Changing the default on Windows is likely to have a negative performance impact. |
threadPriority | (int)The priority of the acceptor and poller threads. The default value is |
useComet | (bool)Whether to allow comet servlets or not. Default value is |
useSendfile | (bool)Use this attribute to enable or disable sendfile capability. The default value is |
更多推荐
所有评论(0)