Created
January 14, 2022 14:32
-
-
Save jkuipers/3928e1392027d2ea06e568d7ac510ec5 to your computer and use it in GitHub Desktop.
Spring Boot (auto-)configuration class that defines an additional Tomcat Connector for health checks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.catalina.connector.Connector; | |
import org.apache.coyote.AbstractProtocol; | |
import org.springframework.boot.context.properties.ConfigurationProperties; | |
import org.springframework.boot.context.properties.EnableConfigurationProperties; | |
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; | |
import org.springframework.boot.web.server.WebServerFactoryCustomizer; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.context.annotation.Profile; | |
@Configuration | |
@EnableConfigurationProperties(TomcatAutoConfiguration.HealthConnectorProperties.class) | |
public class TomcatAutoConfiguration { | |
/** | |
* Creates an addition {@link Connector} for Tomcat that we use for the health checks. | |
* This ensures that even when all the request handling threads from the regular connector | |
* are in use, we can still respond to health check requests made on port 8888. | |
*/ | |
@Profile("!local") | |
@Bean | |
WebServerFactoryCustomizer<TomcatServletWebServerFactory> tomcatHealthConnectorCustomizer(TomcatAutoConfiguration.HealthConnectorProperties connector) { | |
return server -> { | |
Connector healthConnector = new Connector(); | |
healthConnector.setPort(connector.getPort()); | |
AbstractProtocol protocol = (AbstractProtocol) healthConnector.getProtocolHandler(); | |
protocol.setMinSpareThreads(connector.getMinThreads()); | |
protocol.setMaxThreads(connector.getMaxThreads()); | |
server.addAdditionalTomcatConnectors(healthConnector); | |
}; | |
} | |
@ConfigurationProperties("health.connector") | |
public static class HealthConnectorProperties { | |
/** port number used by the addition Tomcat connector for health checks */ | |
private int port = 8888; | |
private int minThreads = 1; | |
private int maxThreads = 5; | |
public int getPort() { | |
return port; | |
} | |
public void setPort(int port) { | |
this.port = port; | |
} | |
public int getMinThreads() { | |
return minThreads; | |
} | |
public void setMinThreads(int minThreads) { | |
this.minThreads = minThreads; | |
} | |
public int getMaxThreads() { | |
return maxThreads; | |
} | |
public void setMaxThreads(int maxThreads) { | |
this.maxThreads = maxThreads; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment