架构设计 - 根据性能压力测试结果优化服务器性能
概述:web软件项目工程实施过程,经常会用到客户端和服务端建立 KeepAlive 长连接来提高应用效率的场景。例如:移动端应用或者复杂的网页交互需要在用户浏览时频繁地向服务端发送请求。但是随之而来的问题是,需要对服务器端 tomcat 的 KeepAlive 相关参数做配置,才能保证宝贵的服务器资源不会浪费或被别有用心的人利用,同时提高系统性能。
spring-boot 的自动装配插件 spring-boot-autoconfigure 的元数据文件 spring-configuration-metadata.json 中已经内嵌了一些默认的 tomcat 配置:
默认情况下,
连接数超过 10000 后会出现拒绝连接的情况。
触发的客户端请求超过 300 后拒绝响应。
{"sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties$Tomcat","defaultValue": 100,"name": "server.tomcat.accept-count","description": "Maximum queue length for incoming connection requests when all possible request processing threads are in use.","type": "java.lang.Integer"},
...{"sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties$Tomcat","defaultValue": 10000,"name": "server.tomcat.max-connections","description": "Maximum number of connections that the server accepts and processes at any given time. Once the limit has been reached, the operating system may still accept connections based on the \"acceptCount\" property.","type": "java.lang.Integer"},
... {"sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties$Tomcat","defaultValue": 200,"name": "server.tomcat.max-threads","description": "Maximum number of worker threads.","type": "java.lang.Integer"},
... {"sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties$Tomcat","defaultValue": 10,"name": "server.tomcat.min-spare-threads","description": "Minimum number of worker threads.","type": "java.lang.Integer"},
但是与 KeepAlive 相关的内嵌 tomcat 配置属性需要定制化开发
// bean被加载后 作用相当于Spring容器内的TomcatEmbeddedServletContainerFactory
@Component
public class WebServerConfiguration implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> {@Overridepublic void customize(ConfigurableWebServerFactory configurableWebServerFactory) {// spring装配工厂类提供了自定义tomcat连接器配置的接口((TomcatServletWebServerFactory)configurableWebServerFactory).addConnectorCustomizers(new TomcatConnectorCustomizer() {@Overridepublic void customize(Connector connector) {Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();// 30秒内没有请求 服务端自动断开 KeepAlive 链接protocol.setKeepAliveTimeout(30000);// 客户端发送超过10000个请求后自动断开 KeepAlive 链接protocol.setMaxKeepAliveRequests(10000);}});}
}