>  기사  >  Java  >  SpringBoot 임의 포트 시작을 구현하는 방법

SpringBoot 임의 포트 시작을 구현하는 방법

PHPz
PHPz앞으로
2023-05-11 17:19:061612검색

1. SpringBoot 임의 포트

1. 기본 소개

  • 임의 포트는 지정된 범위 내에서 사용할 수 있는 포트를 자동으로 찾을 수 있습니다. 구성 파일에 고정된 시작 포트를 지정할 필요가 없습니다. 예를 들어 SpringBoot에서 필요한 경우 여러 인스턴스를 실행하려면 구성 파일을 별도로 수정해야 하는 번거로움이 있습니다. 임의 포트의 원칙은 해당 소켓 포트와 연결을 설정하는 것입니다. 연결이 가능하면 사용되었습니다. 무작위로 얻은 포트 확인 사용 후 System.setProperty("속성 이름", 포트)를 통해 메모리에 쓸 수 있으며 구성 파일에서 얻을 수 있습니다.

  • 쓴 이름이 server.port, 구성 파일에서 포트를 지정할 필요가 없습니다. 그렇지 않으면 server.port=${property name}

  • 을 구성해야 합니다. 이 방법은 SpringBoot 일반 프로젝트를 기반으로 하며 프로젝트 스캐폴딩을 직접 생성하면 됩니다.

  • [tip] 예를 들어 SpringCloud 프로젝트에서 서비스 제공자는 임의의 포트를 사용할 수 있습니다. 구성 파일을 별도로 수정하지 않고도 여러 서비스를 빠르게 시작하고 다시 시작할 수 있습니다

  • 2 구현 단계
  • 만들기. ServerPortUtil.java 포트 도구 클래스, 예를 들어 다음과 같이 소켓을 사용하여 지정된 포트에 연결합니다. Conditions

  • a 포트 범위를 8000-65535
  • b로 지정합니다. 사용 중이면 계속 무작위로 생성됩니다

    c. 모든 포트를 사용할 수 없으면 바로 오류가 발생하고 작업이 중단됩니다.

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

    StartCommand.java 생성 명령 클래스, 임의의 포트 함수를 호출하여 포트 정보를 얻은 다음 실행 중인 환경에 포트 정보를 씁니다
  • a. 수신 매개변수에 포트가 포함되어 있으면 지정된 포트를 사용하고, 그렇지 않으면 자동 생성을 사용합니다
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);
    }
}

포트 정보 쓰기 시작 수업 시작 전 환경

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

구성 파일에 포트를 무작위로 생성된 포트 정보로 지정ServerPortUtil .java端口工具类,使用socket连接指定端口,例如有以下条件

a. 指定端口范围为8000-65535
b. 识别端口是否使用,已被使用则继续随机产生
c. 如果全部端口不可使用则直接抛出错误,中断运行

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

创建StartCommand.javarrreee
프로젝트 테스트는 정상적으로 프로젝트를 시작하며, 시작된 포트 정보는 콘솔에서 확인할 수 있습니다

2. SpringBoot 다중 인스턴스 작업SpringBoot 임의 포트 시작을 구현하는 방법

SpringBoot 다중 인스턴스 작업은 IDEA

SpringBoot 임의 포트 시작을 구현하는 방법

에서 다음과 같이 구성됩니다. 그런 다음 시작 시 실행/디버그를 시작합니다SpringBoot 임의 포트 시작을 구현하는 방법

위 내용은 SpringBoot 임의 포트 시작을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제