Home > Java > javaTutorial > How to implement SpringBoot random port startup

How to implement SpringBoot random port startup

PHPz
Release: 2023-05-11 17:19:06
forward
1676 people have browsed it

1. SpringBoot random port

1. Basic introduction

  • Random port can automatically find ports that can be used within the specified range and does not need to be specified in the configuration file Fixed startup port

  • For example, if you need to run multiple instances in SpringBoot, it is troublesome to modify the configuration file separately

  • Random port The principle is to establish a connection with the corresponding socket port. If it can be connected, it has been used. Otherwise, it has not been used.

  • The randomly obtained port can be used after verification through System.setProperty("Property Name" , port); write to the memory, and then you can get it in the configuration file

  • If the written name is server.port, you do not need to specify the port in the configuration file, otherwise you need to configure it server.port=${property name}

  • This practice is based on SpringBoot ordinary project, just create the project scaffolding directly

  • [tip]For example In the SpringCloud project, the service provider can use random ports to quickly start multiple services without the need to modify the configuration file separately and then start it

2. Implementation steps

CreateServerPortUtil .javaPort tool class, use socket to connect to the specified port, for example, the following conditions are met

a. The specified port range is 8000-65535
b. Identification Whether the port is used, if it is used, it will continue to randomly generate
c. If all ports cannot be used, an error will be thrown directly and the operation will be interrupted.

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 tianxincode@163.com
     * @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;
    }
}
Copy after login

Create the StartCommand.java command class and call The random port function obtains port information, and then writes the port information into the running environment
a. If the incoming parameter contains the port, use the specified one, otherwise use automatic generation

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);
    }
}
Copy after login

Before the startup class is started Write port information to the environment

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);
    }
}
Copy after login

The specified port in the configuration file is randomly generated port information

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

The project test starts the project normally, and you can see the started port information in the console

How to implement SpringBoot random port startup

How to implement SpringBoot random port startup

2. SpringBoot multi-instance operation

The multi-instance operation of SpringBoot is configured as follows in IDEA

How to implement SpringBoot random port startup

How to implement SpringBoot random port startup

#Then run/debug on startup

The above is the detailed content of How to implement SpringBoot random port startup. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template