首页 > 编程语言 > Springboot启用多个监听端口代码实例
2020
10-01

Springboot启用多个监听端口代码实例

前段时间服务有这么个需求,web端的接口需要有web安全相关的整改,但是对内的接口并不需要。所以服务需要多个端口启动,在此记录下

代码如下

@Configuration
public class EmbeddedTomcatConfiguration {
 
  @Value("${server.additionalPorts}")
  private String additionalPorts;
 
  @Bean
  public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
    Connector[] additionalConnectors = this.additionalConnector();
    if (additionalConnectors != null && additionalConnectors.length > 0) {
      tomcat.addAdditionalTomcatConnectors(additionalConnectors);
    }
    return tomcat;
  }
 
  private Connector[] additionalConnector() {
    if (StringUtils.isBlank(this.additionalPorts)) {
      return null;
    }
    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[] {});
  }
}

application.yml

server:
port: ${appPort:8800}
additionalPorts: 8881,8882

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

编程技巧