tomcat 参数配置
官网:Apache Tomcat 10 Configuration Reference (10.0.14) - Overview
*******************
server.xml
默认配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!-- 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" />
<!-- 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="150" minSpareThreads="4"/>
-->
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
HTTP Connector: /docs/config/http.html
AJP Connector: /docs/config/ajp.html
Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
-->
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!-- Define an SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
This connector uses the NIO implementation. The default
SSLImplementation will depend on the presence of the APR/native
library and the useOpenSSL attribute of the AprLifecycleListener.
Either JSSE or OpenSSL style configuration may be used regardless of
the SSLImplementation selected. JSSE style configuration is used below.
-->
<!--
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true">
<UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
<SSLHostConfig>
<Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
type="RSA" />
</SSLHostConfig>
</Connector>
-->
<!-- Define an AJP 1.3 Connector on port 8009 -->
<!--
<Connector protocol="AJP/1.3"
address="::1"
port="8009"
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>
server
className:org.apache.catalina.Server接口的实现类,如果不指定,默认为
org.apache.catalina.core.StandardServer
address:关闭监听ip地址,默认为locahost
port:关闭监听端口,默认为8005,设置为-1表示禁用关闭端口
说明:禁用关闭端口会导致windows(bat)、linux(sh)启动后,不能优雅关闭
portOffset:The offset to apply to port and to the ports of any nested connectors
嵌套连接器的端口偏移量,为非负数,默认为0
shutdown:ip、port收到的用于关闭tomcat的字符串,默认为SHUTDOWN
utilityThreads:The number of threads this Service will use for various utility tasks
执行公共任务的线程数
除以上公共参数外,org.apache.catalina.core.StandardServer包含以下额外参数
utilityThreadsAsDaemon:Set the daemon flag value for the utility threads
执行公共任务的线程数是否在后台执行,默认为false
periodicEventDelay:监听事件生命周期触发的时间间隔,默认为10s
service
className:org.apache.catalina.Service接口实现类,如果不指定,默认为
org.apache.catalina.core.StandardService
name:service的名称
除以上公共参数外,org.apache.catalina.core.StandardService还有一些额外参数
gracefulStopAwaitMillis:优雅关闭等待时间,默认为0
executor
className:org.apache.catalina.Executor接口实现类,如果不指定,默认为
org.apache.catalina.core.StandardThreadExecutor
name:线城池名称
除以上公共参数,org.apache.catalina.core.StandardThreadExecutor额外参数
public class StandardThreadExecutor extends LifecycleMBeanBase implements Executor, ResizableExecutor {
protected static final StringManager sm = StringManager.getManager(StandardThreadExecutor.class);
protected int threadPriority = 5; //线程优先级
protected boolean daemon = true; //是否后台执行
protected String namePrefix = "tomcat-exec-"; //线程名前缀
protected int maxThreads = 200; //最大活跃线程数
protected int minSpareThreads = 25; //最小空闲线程
protected int maxIdleTime = 60000; //最大空闲时间
protected ThreadPoolExecutor executor = null;
protected String name;
protected boolean prestartminSpareThreads = false; //最小空闲数线程是否在线程池启动时启动,默认false
protected int maxQueueSize = 2147483647; //队列长度
protected long threadRenewalDelay = 1000L; //线程更新间隔
private TaskQueue taskqueue = null;
***************
connector 属性
公共属性
public class Connector extends LifecycleMBeanBase {
private static final Log log = LogFactory.getLog(Connector.class);
public static final String INTERNAL_EXECUTOR_NAME = "Internal";
protected Service service;
protected boolean allowBackslash; //是否使用"\"作为路径分隔符,默认false
protected boolean allowTrace; //是否追踪http请求
protected long asyncTimeout; //异步请求超时时间
protected boolean enableLookups; //是否查找DNS,进行host转换
protected boolean enforceEncodingInGetWriter; //Response.getWriter()使用默认编码,默认为true
protected boolean xpoweredBy; //使用servlet规范推荐的header
protected String proxyName; //代理名称,request.getServerName()使用
protected int proxyPort; //代理端口,request.getServerPort()使用
protected boolean discardFacades; //是否丢弃隔离对象,默认为true
protected int redirectPort; //重定向端口,默认443
protected String scheme; //协议名,默认http
protected boolean secure; //是否是安全连接,默认false
protected static final StringManager sm = StringManager.getManager(Connector.class);
private int maxCookieCount; //cookie最大数量,默认200
protected int maxParameterCount; //请求参数最大数量,默认10000
protected int maxPostSize; //请求体最大值,默认2097152(2m)
protected int maxSavePostSize; //最大缓存的请求体,默认4096(4k)
protected String parseBodyMethods; //需要解析的请求方法,默认post
protected HashSet<String> parseBodyMethodsSet;
protected boolean useIPVHosts; //tomcat收到ip请求后,是否识别转发到host,默认false
protected final String protocolHandlerClassName; //使用的协议:Http11NioProtocol、Http11Nio2Protocol、Http11AprProtocol)
//Http11AprProtocol在10.1.x中禁用,之后回移除
protected final String configuredProtocol;
protected final ProtocolHandler protocolHandler;
protected Adapter adapter;
private Charset uriCharset; //uri编码,默认utf-8
private EncodedSolidusHandling encodedSolidusHandling;
protected boolean useBodyEncodingForURI; //是否使用content-type中的编码值对uri请求参数编码
public Connector() {
this("HTTP/1.1");
}
public Connector(String protocol) {
this.service = null;
this.allowBackslash = false;
this.allowTrace = false;
this.asyncTimeout = 30000L;
this.enableLookups = false;
this.enforceEncodingInGetWriter = true;
this.xpoweredBy = false;
this.proxyName = null;
this.proxyPort = 0;
this.discardFacades = true;
this.redirectPort = 443;
this.scheme = "http";
this.secure = false;
this.maxCookieCount = 200;
this.maxParameterCount = 10000;
this.maxPostSize = 2097152;
this.maxSavePostSize = 4096;
this.parseBodyMethods = "POST";
this.useIPVHosts = false;
this.adapter = null;
this.uriCharset = StandardCharsets.UTF_8;
this.encodedSolidusHandling = EncodedSolidusHandling.REJECT;
this.useBodyEncodingForURI = false;
this.configuredProtocol = protocol;
ProtocolHandler p = null;
try {
p = ProtocolHandler.create(protocol);
} catch (Exception var4) {
log.error(sm.getString("coyoteConnector.protocolHandlerInstantiationFailed"), var4);
}
if (p != null) {
this.protocolHandler = p;
this.protocolHandlerClassName = this.protocolHandler.getClass().getName();
} else {
this.protocolHandler = null;
this.protocolHandlerClassName = protocol;
}
this.setThrowOnFailure(Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE"));
}
http connector额外支持的属性
acceptCount:最大接收的请求数
acceptorThreadPriority:线程优先级
address:一个服务器可能有多个ip地址,指定使用的ip地址
allowHostHeaderMismatch:是否允许缺失host header,默认false
allowedTrailerHeaders:允许使用的tailer header,逗号间隔
bindOnInit:端口载启动时绑定,默认true
clientCertProvider:安全证书,默认java.security.cert.X509Certificate
compressibleMimeType:可能使用的http压缩类型,逗号间隔
compression:是否压缩,可选值:on、off、forece
compressionMinSize:最小压缩大小
connectionLinger:连接关闭时,等待时间
connectionTimeout:连接超时时间
connectionUploadTimeout:上传超时时间
disableUploadTimeout:不允许超过设置的上传超时时间,默认false
executor:使用的线程池
executorTerminationTimeoutMillis:线程终止超时时间,默认5s
keepAliveTimeout:http连接空闲时间
maxConnections:最大连接数,默认8192
maxHttpHeaderSize:header最大大小,默认8192 (8k)
maxKeepAliveRequests:请求最大活跃连接数,默认100
maxSwallowSize:终止的上传请求缓存大小
maxThreads:最大处理连接请求的线程数
maxTrailerSize:Limits the total length of trailing headers in the last chunk of a chunked HTTP request
minSpareThreads:最小空闲线程数
noCompressionUserAgents:不压缩的user-agent
processorCache:processor缓存数,默认200
rejectIllegalHeader:拒绝非法header,默认true
relaxedPathChars:允许uri path使用的不符合规范的字符
relaxedQueryChars:允许查询参数中使用的不符合规范的字符
restrictedUserAgents:拒绝使用的user-agents
server:覆盖响应体中的server值
serverRemoveAppProvidedValues:是否移除server header,默认false
SSLEnabled:是否开启ssl
tcpNoDelay:tcp连接不延迟
threadPriority:jvm中的线程优先级
throwOnFailure:是否抛出异常
useAsyncIO:是否使用异步io,默认true
useKeepAliveResponseHeader:是否载response header使用keep-alive,默认true
tcp 连接属性(nio、nio2)
socket.rxBufSize:接收缓存
socket.txBufSize:发送缓存
socket.tcpNoDelay:与标准属性中的tcpNoDelay配置相同
socket.soKeepAlive:Boolean value for the socket's keep alive
socket.ooBInline:(bool)Boolean value for the socket OOBINLINE setting
socket.soReuseAddress:(bool)Boolean value for the sockets reuse address option (SO_REUSEADDR)
socket.soLingerOn:(bool)Boolean value for the sockets so linger option (SO_LINGER)
socket.soLingerTime:(int)Value in seconds for the sockets so linger option
socket.soTimeout:This is equivalent to standard attribute connectionTimeout
socket.performanceConnectionTime:(int)The first value for the performance settings
socket.performanceLatency:(int)The second value for the performance settings
socket.performanceBandwidth:(int)The third value for the performance settings
socket.unlockTimeout:(int) The timeout for a socket unlock
nio 支持的属性
pollerThreadPriority:(int)The priority of the poller threads
selectorTimeout:(int)The time in milliseconds to timeout on a select() for the poller
useSendfile:(bool)Use this attribute to enable or disable sendfile capability
socket.directBuffer:(bool)Boolean value, whether to use direct ByteBuffers or java mapped ByteBuffers
socket.directSslBuffer:(bool)Boolean value, whether to use direct ByteBuffers or java mapped ByteBuffers for the SSL buffers
socket.appReadBufSize:(int)Each connection that is opened up in Tomcat get associated with a read ByteBuffer
socket.appWriteBufSize:(int)Each connection that is opened up in Tomcat get associated with a write ByteBuffer
socket.bufferPool:(int)The NIOx connector uses a class called NioXChannel that holds elements linked to a socket
socket.bufferPoolSize:(int)The NioXChannel pool can also be size based, not used object based
socket.processorCache:(int)Tomcat will cache SocketProcessor objects to reduce garbage collection
socket.eventCache:(int)Tomcat will cache PollerEvent objects to reduce garbage collection
unixDomainSocketPath:Where supported, the path to a Unix Domain Socket that this Connector will create and await incoming connections
unixDomainSocketPathPermissions:Where supported, the posix permissions that will be applied to the to the Unix Domain Socket specified with unixDomainSocketPath above
useInheritedChannel:(bool)Defines if this connector should inherit an inetd/systemd network socket
nio2 支持的属性
useSendfile:(bool)Use this attribute to enable or disable sendfile capability
socket.directBuffer:(bool)Boolean value, whether to use direct ByteBuffers or java mapped ByteBuffers
socket.directSslBuffer:(bool)Boolean value, whether to use direct ByteBuffers or java mapped ByteBuffers for the SSL buffers
socket.appReadBufSize:(int)Each connection that is opened up in Tomcat get associated with a read ByteBuffer
socket.appWriteBufSize:(int)Each connection that is opened up in Tomcat get associated with a write ByteBuffer
socket.bufferPool:(int)The NIO2 connector uses a class called Nio2Channel that holds elements linked to a socket
socket.processorCache:(int)Tomcat will cache SocketProcessor objects to reduce garbage collection
嵌套子元素:http2支持
<Connector ... >
<!-- 添加UpgradeProtocol,即可升级到http2 -->
<UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
</Connector>
嵌套子元素:ssl支持
# SSLHostConfig
certificateRevocationListFile:Name of the file that contains the concatenated certificate revocation lists for the certificate authorities
certificateRevocationListPath:Name of the directory that contains the certificate revocation lists for the certificate authorities
certificateVerification:证书认证方式,可选值:required、optional、optionalNoCA、none(默认)
certificateVerificationDepth:The maximum number of intermediate certificates that will be allowed when validating client certificates,默认10
caCertificateFile:Name of the file that contains the concatenated certificates for the trusted certificate authorities
caCertificatePath:Name of the directory that contains the certificates for the trusted certificate authorities
ciphers:The ciphers to enable using the OpenSSL syntax
disableCompression:Configures if compression is disabled
disableSessionTickets:Disables use of TLS session tickets
honorCipherOrder:Set to true to enforce the server's cipher order (from the ciphers setting) instead of allowing the client to choose the cipher,默认false
hostName:主机名
insecureRenegotiation:Configures if insecure renegotiation is allowed
keyManagerAlgorithm:keyManager算法
protocols:支持的协议
revocationEnabled:Should the JSSE provider enable certificate revocation checks
sessionCacheSize:session缓存大小
sessionTimeout:session超时时间
sslProtocol:ssl协议,默认TLS
trustManagerClassName:The name of a custom trust manager class to use to validate client certificates
truststoreAlgorithm:The algorithm to use for truststore
truststoreFile:The trust store file to use to validate client certificates
truststorePassword:The password to access the trust store
truststoreProvider:The name of the truststore provider to be used for the server certificate
truststoreType:The type of key store used for the trust store
# Certificate
certificateFile:Name of the file that contains the server certificate
certificateChainFile:Name of the file that contains the certificate chain associated with the server certificate used
certificateKeyAlias:The alias used for the server key and certificate in the keystore
certificateKeyFile:Name of the file that contains the server private key
certificateKeyPassword:The password used to access the private key associated with the server certificate from the specified file
certificateKeystoreFile:The pathname of the keystore file where you have stored the server certificate and key to be loaded
certificateKeystorePassword:The password to use to access the keystore containing the server's private key and certificate
certificateKeystoreProvider:The name of the keystore provider to be used for the server certificate
certificateKeystoreType:The type of keystore file to be used for the server certificate
type:The type of certificate
# 示例
<Connector
protocol="org.apache.coyote.http11.Http11AprProtocol"
port="8443"
maxThreads="150"
SSLEnabled="true" >
<SSLHostConfig>
<Certificate
certificateKeyFile="conf/localhost-rsa-key.pem"
certificateFile="conf/localhost-rsa-cert.pem"
certificateChainFile="conf/localhost-rsa-chain.pem"
type="RSA"
/>
</SSLHostConfig>
</Connector>
http2 支持的属性
initialWindowSize:初始窗口大小
keepAliveTimeout:空闲连接存活时间
maxConcurrentStreamExecution:最大并行数
maxConcurrentStreams:最大活跃并行数
maxHeaderCount:最大header数
maxTrailerCount:最大的tailer header数
overheadContinuationThreshold:连续负载阀值
overheadCountFactor:The factor to apply when counting overhead frames to determine if a connection has too high an overhead and should be closed
overheadDataThreshold:The threshold below which the average payload size of the current and previous non-final DATA frames will trigger an increase in the overhead count
overheadWindowUpdateThreshold:The threshold below which the average size of current and previous WINDOW_UPDATE frame will trigger an increase in the overhead count (see overheadCountFactor)
readTimeout:读取超时时间
writeTimeout:写入超时时间
streamReadTimeout:流式读取超时时间
streamWriteTimeout:流式写入超时时间
useSendfile:是否使用sendfile,默认true
*******************
springboot 对应配置类
ServerProperties
@ConfigurationProperties(
prefix = "server",
ignoreUnknownFields = true
)
public class ServerProperties {
private Integer port;
private InetAddress address;
@NestedConfigurationProperty
private final ErrorProperties error = new ErrorProperties();
private ServerProperties.ForwardHeadersStrategy forwardHeadersStrategy;
private String serverHeader;
private DataSize maxHttpHeaderSize = DataSize.ofKilobytes(8L);
private Shutdown shutdown;
@NestedConfigurationProperty
private Ssl ssl;
@NestedConfigurationProperty
private final Compression compression;
@NestedConfigurationProperty
private final Http2 http2;
private final ServerProperties.Servlet servlet;
private final ServerProperties.Reactive reactive;
private final ServerProperties.Tomcat tomcat;
private final ServerProperties.Jetty jetty;
private final ServerProperties.Netty netty;
private final ServerProperties.Undertow undertow;
**********
内部类:Tomcat
public static class Tomcat {
private final ServerProperties.Tomcat.Accesslog accesslog = new ServerProperties.Tomcat.Accesslog();
private final ServerProperties.Tomcat.Threads threads = new ServerProperties.Tomcat.Threads();
private File basedir;
@DurationUnit(ChronoUnit.SECONDS)
private Duration backgroundProcessorDelay = Duration.ofSeconds(10L);
private DataSize maxHttpFormPostSize = DataSize.ofMegabytes(2L);
private DataSize maxSwallowSize = DataSize.ofMegabytes(2L);
private Boolean redirectContextRoot = true;
private boolean useRelativeRedirects;
private Charset uriEncoding;
private int maxConnections;
private int acceptCount;
private int processorCache;
private Duration keepAliveTimeout;
private int maxKeepAliveRequests;
private List<String> additionalTldSkipPatterns;
private List<Character> relaxedPathChars;
private List<Character> relaxedQueryChars;
private Duration connectionTimeout;
private boolean rejectIllegalHeader;
private final ServerProperties.Tomcat.Resource resource;
private final ServerProperties.Tomcat.Mbeanregistry mbeanregistry;
private final ServerProperties.Tomcat.Remoteip remoteip;
public Tomcat() {
this.uriEncoding = StandardCharsets.UTF_8;
this.maxConnections = 8192;
this.acceptCount = 100;
this.processorCache = 200;
this.maxKeepAliveRequests = 100;
this.additionalTldSkipPatterns = new ArrayList();
this.relaxedPathChars = new ArrayList();
this.relaxedQueryChars = new ArrayList();
this.rejectIllegalHeader = true;
this.resource = new ServerProperties.Tomcat.Resource();
this.mbeanregistry = new ServerProperties.Tomcat.Mbeanregistry();
this.remoteip = new ServerProperties.Tomcat.Remoteip();
}
SSL
public class Ssl {
private boolean enabled = true;
private Ssl.ClientAuth clientAuth;
private String[] ciphers;
private String[] enabledProtocols;
private String keyAlias;
private String keyPassword;
private String keyStore;
private String keyStorePassword;
private String keyStoreType;
private String keyStoreProvider;
private String trustStore;
private String trustStorePassword;
private String trustStoreType;
private String trustStoreProvider;
private String protocol = "TLS";