栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot 项目中随机生成程序运行端口(项目端口自定义)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot 项目中随机生成程序运行端口(项目端口自定义)

文章目录
  • 前言


前言

最近在开发一个客户端运行的服务程序,考虑到不需要用户知道程序使用的哪个端口,也不需要用户去配置运行的端口,索性就有程序自动随机的使用一个端口。如果是这样还得考虑到所使用的端口是否有被占用而导致这个服务程序无法正常启动的情况。
这里使用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;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/584386.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号