gpt4 book ai didi

spring-boot - 给定范围内的随机服务器端口spring boot

转载 作者:行者123 更新时间:2023-12-02 00:59:25 39 4
gpt4 key购买 nike

我想在给定范围 (5001-5100) 的随机端口上启动 Spring Cloud 应用程序(Spring Boot 1.5.14,Spring Cloud Edgware.SR4)。我知道我们可以使用 server.port=0 在 Spring Boot 应用程序中指定随机端口,但我面临以下两个问题:

  • 选择给定范围内的动态可用端口 [5000-5100]
  • 当我使用 server.port=0 时, Eureka 注册表显示端口为 0 ,spring cloud是否支持动态端口?
  • 最佳答案

    Spring 提供了实用程序类来扫描可用的 TCP 端口,因此我使用以下方法设置随机服务器端口。

    public static void setRandomPort(int minPort, int maxPort) {
    try {
    String userDefinedPort = System.getProperty("server.port", System.getenv("SERVER_PORT"));
    if (StringUtils.isEmpty(userDefinedPort)) {
    int port = SocketUtils.findAvailableTcpPort(minPort, maxPort);
    System.setProperty("server.port", String.valueOf(port));
    log.info("Server port set to {}.", port);
    }
    } catch (IllegalStateException var4) {
    log.warn("No port available in range 5000-5100. Default embedded server configuration will be used.");
    }
    }

    现在这个方法可以在启动 spring 上下文之前在 Spring Boot Application 的主类中调用,就像这样:
    public static void main(String[] args) {
    setRandomPort();
    ApplicationContext ctx = SpringApplication.run(Application.class, args);
    logger.info("Application " + ctx.getApplicationName() + " started");
    }

    现在这个随机端口配置在 Spring Cloud 环境中工作正常。

    关于spring-boot - 给定范围内的随机服务器端口spring boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51665134/

    39 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com