springboot2.0服务配置两个端口
时间: 2023-12-17 09:03:13 浏览: 33
在Spring Boot 2.0及以上版本中,可以通过以下步骤配置两个端口:
1. 在`application.properties`或`application.yml`配置文件中添加以下属性:
```yaml
server.port=8080
# 添加第二个端口配置
server.additional-ports=9090
```
2. 创建一个自定义的`WebServerFactoryCustomizer` bean,并在其中进行端口配置。可以在应用的主类上添加`@Configuration`注解,并定义一个bean方法来创建自定义的`WebServerFactoryCustomizer`。
```java
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServerConfig {
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
return (WebServerFactoryCustomizer<ConfigurableWebServerFactory>) factory -> {
if (factory instanceof ConfigurableServletWebServerFactory) {
// 配置第二个端口
((ConfigurableServletWebServerFactory) factory).setPort(9090);
}
};
}
}
```
这里使用了`ConfigurableServletWebServerFactory`来进行配置。通过创建一个自定义的`WebServerFactoryCustomizer` bean,并实现`WebServerFactoryCustomizer<ConfigurableWebServerFactory>`接口,在`customize()`方法中对第二个端口进行配置。
这样配置完成后,你的Spring Boot应用就会同时监听8080和9090两个端口。你可以根据需求进行相应的调整。