如何为我的 spring-boot 应用程序中嵌入的 Web 服务器 (Tomcat) 配置低级套接字属性?

How to configure low-level socket properties for a web server (Tomcat) embedded in my spring-boot application?

如何为 spring-boot 嵌入式 Web 服务器配置低级选项(在我的具体案例中,我使用的是 Tomcat)?

例如,我想将 SO_REUSEADDR 设置为 true。

这个答案是Tomcat-specific

事实证明这可以通过 TomcatConnectorCustomizer 个 beans,例如

@Bean
public TomcatConnectorCustomizer tomcatConnectorCustomizer() {
    return connector -> connector.setProperty("socket.soReuseAddress", "true");
}

它是如何工作的?

connector.setProperty 是通过 IntrospectionUtils.setProperty 实现的,它会查找具有匹配名称的 bean 属性,如果失败,则在连接器的 ProtocolHandler 中查找 uses a getProperty method

在我的例子中,ProtocolHandler 是 org.apache.coyote.http11.Http11NioProtocol,它有一个 setProperty in its superclass org.apache.coyote.AbstractProtocol, that in the end invokes org.apache.tomcat.util.net.AbstractEndpoint's setProperty

那就是那个方法differentiates properties with socket. prefix, and again reflectively matches it to org.apache.tomcat.util.net.SocketProperties accessors (in our case setSoReuseAddress).

最后,当创建套接字时,the stored configuration is used 配置新套接字时。


还应注意(同样,这是 Tomcat 特定的)Tomcat 也使用 JVM 默认值 (link)。