1.springboot2.x以前
@Configuration
@ConditionalOnProperty(value = "server.additionPort.enable", havingValue = "true")
@ConditionalOnClass(value = EmbeddedServletContainerCustomizer.class)
public class EmbeddedTomcatConfiguration implements EmbeddedServletContainerCustomizer {
@Value("${server.additionPort.ports:}")
private String additionalPorts;
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
// 判断如果是Tomcat才进行如下配置
if (container instanceof TomcatEmbeddedServletContainerFactory) {
// 转类型为TomcatEmbeddedServletContainerFactory
TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
String[] split = additionalPorts.split(",");
for (String port : split) {
// Tomcat中,一个Connecter监听一个端口
// 指定协议为HTTP/1.1
Connector httpConnector = new Connector("HTTP/1.1");
httpConnector.setPort(Integer.parseInt(port));
tomcat.addAdditionalTomcatConnectors(httpConnector);
}
}
}
}
2.springboot2.x以后
@Component
@ConditionalOnProperty(value = "server.additionPort.enable", havingValue = "true")
@ConditionalOnClass(value = TomcatServletWebServerFactory.class)
public class EmbeddedTomcatConfiguration {
@Value("${server.additionPort.ports:}")
private String additionalPorts;
@Bean
public TomcatServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
Connector[] additionalConnectors = this.additionalConnector();
if (additionalConnectors != null && additionalConnectors.length > 0) {
tomcat.addAdditionalTomcatConnectors(additionalConnectors);
}
return tomcat;
}
private Connector[] additionalConnector() {
String[] ports = this.additionalPorts.split(",");
List<Connector> result = new ArrayList<>();
for (String port : ports) {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(Integer.valueOf(port));
result.add(connector);
}
return result.toArray(new Connector[] {});
}
}