在Spring boot中指定随机可用的端口

​ 正常情况下每个spring boot启动都有固定的端口,也就是8080,如果启动多个项目,很容易出现端口冲突,那么怎么解决这个问题呢?

解决方案1: random 随机端口

​ 在spring boot中,可以通过${random}来生成随机数字,b那么我们就可以在配置文件中,这样设置端口:

server:
  port: ${random.int(2000, 65535}

​ 通过random.int()方法,指定生成2000~65535的随机端口。这样每次启动的端口都不一样。但是这样就可以了吗?不是的,我们随机生辰的端口也会有可能被其他的进程所占用。

​ 那么,我们能否通过一个检测机制,让生成的随机端口一定是一个没有被占用的有效的随机端口呢?

​ 我们可以使用socket 建立一个和随机端口号的连接,如果能建立一个socket则说明该主机的该端口在使用。

解决方案2: 有效端口检测

实现思路:

​ 通过在项目启动前,获取有效的随机端口并通过System.setProperty将变量设置到系统的全局变量中,这样项目启动时就可以从全局变量中获取到server.port变量的值。

​ 这里的system,系统指的是 JRE (runtime)system,即设置jvm运行时的全局变量。

工具类:

​ NetUtils.java

@Slf4j
public class NetUtils {

    private static final Random random = new Random();

    /**
     * 获取可用端口
     *
     * @return 可以使用端口
     */
    public static int getAvailablePort() {
        int max = 65535;
        int min = 2000;
        int port = random.nextInt(max) % (max - min + 1) + min;
        boolean using = isPortUsing(port);
        log.info("正在测试端口:{} 是否可用", port);
        if (using) {
            log.info("端口:{} 可用", port);
        } else {
            log.info("端口:{} 不可用,重新获取端口", port);
        }
        return using ? port : getAvailablePort();
    }

    /**
     * 检查端口是否可用
     *
     * @param port 端口号
     * @return true 可用  false 不可用
     */
    public static boolean isPortUsing(int port) {

        boolean flag = true;
        try {
            InetAddress address = InetAddress.getByName("127.0.0.1");
            // 建立一个 socket连接
            new Socket(address, port).close();  //建立一个Socket连接
            flag = false;
        } catch (Exception ignored) {

        }
        return flag;
    }
    
}

项目启动前设置server.port环境变量

​ StartCommand.java

/**
 * 该类为 springboot 启动时候配置端口的命令类
 */
@Slf4j
public class StartCommand {

    public StartCommand() {
        int port = NetUtils.getAvailablePort();
        System.setProperty("server.port", String.valueOf(port));
        log.info("\n-----------最终的端口为{}----------------------最终的端口为{}-----------", port, port);
    }

}

在 Springboot 启动类调用该方法

@SpringBootApplication
public class InterfacesApplication {

    public static void main(String[] args) {
        new StartCommand();
        SpringApplication.run(InterfacesApplication.class, args);
        System.out.println("\n-----------接口启动成功----------------------接口启动成功-----------");
    }

}

最后在启动后每次都说不同的端口了

在这里插入图片描述

在这里插入图片描述

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值