vlambda博客
学习文章列表

Web容器性能相关:keepalive

Web容器的keepalive一般有2个属性:

keepAliveTimeout:表示在下次请求过来之前,tomcat保持该连接多久。这就是说假如客户端不断有请求过来,且为超过过期时间,则该连接将一直保持。 

maxKeepAliveRequests:表示该连接最大支持的请求数。超过该请求数的连接也将被关闭(此时就会返回一个Connection: close头给客户端)。 

MaxKeepAliveRequests指令限制了当启用KeepAlive时,每个连接允许的请求数量。如果将此值设为"0",将不限制请求的数目。我们建议最好将此值设为一个比较大的值,以确保最优的服务器性能。


以tomcat为例,通过配置server.xml可以修改这2个值:

<Connector port="${tomcat.http.port}"                         protocol="org.apache.coyote.http11.Http11NioProtocol"        connectionTimeout="20000"         redirectPort="${tomcat.redirect.port}"        maxThreads="1000"        minSpareThreads="100"        acceptCount="500"        keepAliveTimeout="300000"        maxKeepAliveRequests="1000"        enableLookups="false"        compression="off"        URIEncoding="UTF-8" server="webserver" />

而spring boot容器比较坑则需要自定义容器工厂来修改这2个值:

@Configurationpublic class SpringBootDeploy {
private static final Logger log = LoggerFactory.getLogger(AppConfiguration.class);

@Value("${custom.tomcat.keepAliveTimeout}") private int tomcatKeepAliveTimeout;
@Value("${custom.tomcat.maxKeepAliveRequests}") private int maxKeepAliveRequests;

@Bean public TomcatServletWebServerFactory getEmbeddedServletContainerFactory() { TomcatServletWebServerFactory containerFactory = new TomcatServletWebServerFactory(); containerFactory .addConnectorCustomizers(new TomcatConnectorCustomizer() { @Override public void customize(Connector connector) { AbstractHttp11Protocol protocol = (AbstractHttp11Protocol) connector.getProtocolHandler(); int originMaxKeepAliveRequests = protocol.getMaxKeepAliveRequests(); protocol.setMaxKeepAliveRequests(maxKeepAliveRequests); int originKeepAliveTimeout = protocol.getKeepAliveTimeout(); protocol.setKeepAliveTimeout(tomcatKeepAliveTimeout);
log.info( "####################################################################################"); log.info("#"); log.info("# TomcatCustomizer"); log.info("#"); log.info("# origin maxKeepAliveRequests {}", originMaxKeepAliveRequests); log.info("# custom maxKeepAliveRequests {}", protocol.getMaxKeepAliveRequests()); log.info("# origin keepalive timeout: {} ms", originKeepAliveTimeout); log.info("# keepalive timeout: {} ms", protocol.getKeepAliveTimeout()); log.info("# connection timeout: {} ms", protocol.getConnectionTimeout()); log.info("# max connections: {}", protocol.getMaxConnections()); log.info("#"); log.info( "####################################################################################"); } });
return containerFactory; }}