Springboot单机多副本运行,解决端口冲突

一、不启动端口方式(仅支持定时、kafka等任务,不支持get/post)

spring:
  main:
    web-application-type: none

eureka客户端唯一id采用随机数

eureka:
  instance:
    instance-id: ${spring.cloud.client.ip-address}:${random.int(10000, 65536)}

二、将随机端口设置为全局系统属性,在配置和代码中引用

public class Application {
    public static void main(String[] args) {
        System.setProperty("my.port", String.valueOf(new Random().nextInt(55536) + 10000));
        SpringApplication application = new SpringApplication(Application.class);
        application.run(args);
    }
}

配置中引用:

eureka:
  instance:
    instance-id: ${spring.cloud.client.ip-address}:${my.port}

配置类中引用:

@Value("${my.port}")
private int myport;

@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> MyCustomizer(){
    return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
        @Override
        public void customize(ConfigurableWebServerFactory factory) {
            factory.setPort(myport);
        }
    };
}

 

posted @ 2024-05-10 19:12  凤凰涅磐欲重生  阅读(24)  评论(0编辑  收藏  举报