项目中,需要配置服务对外提供多个不同的端口,以保证访问不同的服务,进行不同业务的处理。使用的是Springboot+Undertow服务容器的方式。
1. undertow依赖的pom文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
2. 多端口配置
首先需要在配置文件中,增加一个多端口配置的字段,用于配置除过原有server.port之外的端口。我这里配的是additional-ports
字段:
server:
port: 8010
## 支持的多端口监听,中间用,隔开,连续端口使用-进行链接
additional-ports: 8888,8889-8892
其次需要新增config类, 将配置的端口加入启动时的端口监听中。我这里创建的类名为MultiplePortListerConfig,代码如下:
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author:
* @date: 2022-12-16 18:14
* @description: 配置undertow监听多端口
*/
@Configuration
public class MultiplePortListerConfig {
/**
* 额外端口监听
*/
@Value("${server.additional-ports}")
private String additionalPorts;
@Bean
public ServletWebServerFactory undertowFactory() {
UndertowServletWebServerFactory undertowFactory = new UndertowServletWebServerFactory();
undertowFactory.addBuilderCustomizers(builder -> {
if (StrUtil.isBlank(additionalPorts)) {
return;
}
String[] ports = additionalPorts.split(",");
for (String port : ports) {
if (port.contains("-")){
String[] portArr = port.split("-");
int start = Integer.parseInt(StrUtil.trim(portArr[0]));
int end = Integer.parseInt(StrUtil.trim(portArr[1]));
for (int i = start; i<=end; i++){
builder.addHttpListener(i, "0.0.0.0");
}
}else {
builder.addHttpListener(Integer.parseInt(StrUtil.trim(port)), "0.0.0.0");
}
}
});
return undertowFactory;
}
}
启动后,可以看见控制台出现同时监听8010,8888,8889,8890,8891,8892的信息:
调用不同端口访问服务均可访问成功,证明配置成功。