在Spring Boot中,如果你想要让一个应用同时监听多个端口,你可以通过配置多个ServerProperties bean来实现。以下是一个简单的例子:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
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;
 
@SpringBootApplication
public class MultiPortApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(MultiPortApplication.class, args);
    }
 
    @Configuration
    public static class MultipPortConfig {
 
        @Bean
        @ConfigurationProperties(prefix = "server.port1")
        public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> customizer1() {
            return server -> server.setPort(8080);
        }
 
        @Bean
        @ConfigurationProperties(prefix = "server.port2")
        public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> customizer2() {
            return server -> server.setPort(8081);
        }
    }
}在application.properties或application.yml中,你需要添加对应的配置:
# application.properties
server.port1=8080
server.port2=8081或者
# application.yml
server:
  port1: 8080
  port2: 8081这样,你的Spring Boot应用就会同时监听8080和8081端口。你可以根据需要创建更多的customizer方法和相应的配置属性来监听更多的端口。