SpringBoot使用随机端口启动

1.获取可用端口工具类

import java.net.InetAddress;
import java.net.Socket;
import java.util.Random;

public class ServerPortUtil {
    private static final int MAX_PORT = 65535;
    private static final int MIN_PORT = 8000;

    public static String getAvailablePort() {
        Random random = new Random();
		// 最大尝试次数为端口范围
        int maxRetryCount = MAX_PORT - MIN_PORT;
        while (maxRetryCount > 0) {
        	// 指定范围内随机端口,随便写的算法,根据自己需要调整
            int port = random.nextInt(MAX_PORT - MIN_PORT) + MIN_PORT;
            boolean isUsed = isLocalePortUsing(port);
            if (!isUsed) {
                return String.valueOf(port);
            }
            --maxRetryCount;
        }
        System.out.println("系统暂无端口可用,运行结束");
        System.exit(1);
        return null;
    }

    /**
     * 检查给定端口是否可用
     *
     * @author [email protected]
     * @since 2020/10/14
     */
    public static boolean isLocalePortUsing(int port) {
        try {
            // 建立一个Socket连接, 如果该端口还在使用则返回true, 否则返回false, 127.0.0.1代表本机
            new Socket(InetAddress.getByName("127.0.0.1"), port);
            return true;
        } catch (Exception e) {
            // 异常说明端口连接不上,端口能使用
        }
        return false;
    }
}

2.获取到可用端口将端口信息写入运行环境中

import com.codecoord.randomport.util.ServerPortUtil;
import org.springframework.util.StringUtils;

public class StartCommand {
    /**
     * 端口属性名称,如果名称为server.port则在配置文件中不用指定,否则需要指定为此处配置的名称,如${auto.port}
     */
    private static final String SERVER_PORT = "auto.port";

    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;
                }
            }
        }

        String port;
        if (isServerPort) {
           port = serverPort.split("=")[1];
        } else {
            port = ServerPortUtil.getAvailablePort();
        }
        System.out.println("Current project port is " + port);
        System.setProperty(SERVER_PORT, port);
    }
}

3.SpringBoot启动前调用 

import com.codecoord.randomport.config.StartCommand;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplicatio
public class SpringbootRandomPortApplication {
    public static void main(String[] args) {
        // 写入端口信息 
        new StartCommand(args);
        SpringApplication.run(SpringbootRandomPortApplication.class, args);
    }
}

4.修改配置文件

server:
  # 随机端口配置
  port: ${auto.port}

你可能感兴趣的:(SpringBoot,spring,boot,java,后端)