Springboot 项目中随机生成程序运行端口(项目端口自定义)

本文介绍了如何在SpringBoot2.0中实现程序启动时自动随机选择端口,并检查端口是否已被占用。通过实现WebServerFactoryCustomizer接口,自定义配置服务器端口,结合Socket连接测试判断端口可用性,确保服务程序能够顺利启动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章目录


前言

最近在开发一个客户端运行的服务程序,考虑到不需要用户知道程序使用的哪个端口,也不需要用户去配置运行的端口,索性就有程序自动随机的使用一个端口。如果是这样还得考虑到所使用的端口是否有被占用而导致这个服务程序无法正常启动的情况。
这里使用Spring Boot 2.0 中,可通过 WebServerFactoryCustomizer 接口定制功能,对运行程序的端口进行自定义分配。
代码如下:

package com.chqiuu.test;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.server.WebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;

@Slf4j
@EnableConfigurationProperties
@EnableScheduling
@SpringBootApplication
public class SlaveApplication implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

    public static void main(String[] args) {
        System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3");
        SpringApplication.run(SlaveApplication.class, args);
        log.info("客户端启动完成!");
    }

    /**
     * 随机生成程序运行端口
     * Customize the specified {@link WebServerFactory}.
     *
     * @param factory the web server factory to customize
     */
    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        int port = 8080;
        Random rand = new Random();
        int maxPort = 65535;
        int minPort = 10000;
        port = rand.nextInt(maxPort - minPort + 1) + minPort;
        // 端口是否被占用
        boolean used = true;
        while (used) {
            if (isLocalPortUsing(port)) {
                port = rand.nextInt(maxPort - minPort + 1) + minPort;
            } else {
                used = false;
            }
        }
        // 关键代码 设置端口
        factory.setPort(port);
    }

    /**
     * 测试本机端口是否被使用
     *
     * @param port 端口号
     * @return 端口是否被占用
     */
    private boolean isLocalPortUsing(int port) {
        boolean flag = true;
        try {
            //如果该端口还在使用则返回true,否则返回false,127.0.0.1代表本机
            flag = isPortUsing("127.0.0.1", port);
        } catch (Exception ignored) {
        }
        return flag;
    }

    /***
     * 测试主机Host的port端口是否被使用
     * @param host IP
     * @param port 端口号
     * @throws UnknownHostException
     * @return 端口是否被占用
     */
    private boolean isPortUsing(String host, int port) throws UnknownHostException {
        boolean flag = false;
        InetAddress inetAddress = InetAddress.getByName(host);
        try {
            //建立一个Socket连接
            new Socket(inetAddress, port);
            flag = true;
        } catch (IOException ignored) {

        }
        return flag;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码觉客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值