springboot项目启动产生随机端口号并校验该端口号是否被占用

当一个springboot应用想要启动多个实例时,最简单的是改变端口,在服务启动的时候能随机生成一个可以使用的端口是最好不过的,你就不需要手动的去修改application.properties文件手动的去修改然后重启项目费时费力。

不多说直接上代码:

public class StartCommand {
    private Logger logger = LoggerFactory.getLogger(StartCommand.class);


    public StartCommand(String[] args) {
        Boolean isServerPort = false;
        String serverPort = "";
        if (args != null) {
            for (String arg : args) {
                if (StringUtils.hasText(arg) && arg.startsWith("--server.port")) {
                    isServerPort = true;
                    serverPort = arg;
                    break;
                }
            }
        }
        // 没有指定端口, 则随机生成一个可用的端口
        if (!isServerPort) {
            int port = ServerPortUtils.getAvailablePort();
            logger.info("current server.port=" + port);
            System.setProperty("server.port", String.valueOf(port));
        } else {
            logger.info("current server.port=" + serverPort.split("=")[1]);
            System.setProperty("server.port", serverPort.split("=")[1]);
        }
    }
}

方法中调用了:ServerPortUtils.getAvailablePort()工具类。

public class ServerPortUtils {

    public static int getAvailablePort() {
        int max = 65535;
        int min = 2000;
        Random random = new Random();

        int port = random.nextInt(max)%(max-min+1) + min;
        boolean using = NetUtils.isLoclePortUsing(port);
        if (using) {
            return getAvailablePort();
        } else {
            return port;
        }
    }


}

调用的方法:

mport java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @program: springboot-demo
 *
 * @description:
 *
 * @author: Mr.lu
 *
 * @create: 2020-08-19 10:39
 **/
public class NetUtils {


    /***
     *  true:already in using  false:not using
     * @param port
     */
    public static boolean isLoclePortUsing(int port){
        boolean flag = true;
        try {
            flag = isPortUsing("127.0.0.1", port);
        } catch (Exception e) {
        }
        return flag;
    }


    /***
     *  true:already in using  false:not using
     * @param host
     * @param port
     * @throws UnknownHostException
     */
    public static boolean isPortUsing(String host,int port) throws UnknownHostException {
        boolean flag = false;
        InetAddress theAddress = InetAddress.getByName(host);
        try {
            Socket socket = new Socket(theAddress,port);
            flag = true;
        } catch (IOException e) {

        }
        return flag;
    }
}

如何调用:

@SpringBootApplication
public class SpringbootDemoApplication {

    public static void main(String[] args) {
          new StartCommand(args);
          SpringApplication.run(SpringbootDemoApplication.class, args);
    }

}

 

你可能感兴趣的:(java,java)