0.背景
在最开始时,我们指明:
server.port = 9595
这样,springboot程序启动后就会监听9595端口.
但是,碰到一些特殊情场景时,需要加新的监听端口?
1.配置文件中声明要增加的端口
# 用,分割,末尾没有点哈
server.additionalPorts: 2080,2022
2.编写配置类
package com.xx;
import org.apache.catalina.connector.Connector;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
/**
* @Description: 增加端口监听
* @Class: TomcatConfig
* @Author: Yiang37
* @Date: 2021/9/3 15:56
* @Version: 1.0
*/
@Configuration
public class TomcatConfig {
@Value("${server.additionalPorts}")
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() {
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.parseInt(port));
result.add(connector);
}
return result.toArray(new Connector[] {});
}
}
3.启动时声明上面的配置类
package com.xx;
import com.xx.TomcatConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;
// 增加端口监听
@Import({TomcatConfig.class})
@SpringBootApplication
@Slf4j
public class WkgApplication {
public static void main(String[] args) {
SpringApplication.run(WkgApplication.class, args);
log.info("
-------------------------------------------------
" +
"xx run success...
" +
"-------------------------------------------------");
}
}