- 前言
前言
最近在开发一个客户端运行的服务程序,考虑到不需要用户知道程序使用的哪个端口,也不需要用户去配置运行的端口,索性就有程序自动随机的使用一个端口。如果是这样还得考虑到所使用的端口是否有被占用而导致这个服务程序无法正常启动的情况。
这里使用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{ public static void main(String[] args) { System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3"); SpringApplication.run(SlaveApplication.class, args); log.info("客户端启动完成!"); } @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); } 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; } 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; } }



