You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot如何配置端口黑名单/排除列表 避免启动端口冲突

实现Spring Boot服务启动端口排除(黑名单)方案

Spring Boot官方没有内置端口排除的原生配置,你可以通过自定义Web服务器工厂定制器实现需求,支持你提到的exclude.ports配置格式。

步骤1:新增端口排除配置

在application.properties(或application.yml)中添加排除端口配置:

# 逗号分隔需要排除的端口列表
exclude.ports=18080,28080
# 启用随机端口(如果不需要固定端口可自行设置固定值)
server.port=0

步骤2:编写自定义端口定制逻辑

以下是Servlet栈Spring Boot应用的实现代码,如果是WebFlux响应式栈,替换ConfigurableServletWebServerFactory为ConfigurableReactiveWebServerFactory即可:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.net.ServerSocket;
import java.util.List;
import java.util.Random;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ExcludedPortsCustomizer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

    @Value("${exclude.ports:}")
    private List<Integer> excludePorts;

    private final Random random = new Random();
    // 可选端口范围,可根据业务需求调整
    private static final int MIN_PORT = 10000;
    private static final int MAX_PORT = 65535;

    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        // 仅当配置为随机端口(server.port=0)时触发自定义端口选择,不需要可删除该判断
        if (factory.getPort() == 0) {
            int validPort = getValidAvailablePort();
            factory.setPort(validPort);
        } else {
            // 可选逻辑:如果用户指定的固定端口在排除列表中,抛出异常阻止启动
            if (excludePorts.contains(factory.getPort())) {
                throw new IllegalArgumentException("配置的端口 " + factory.getPort() + " 在端口排除列表中,请更换端口");
            }
        }
    }

    private int getValidAvailablePort() {
        int port;
        while (true) {
            // 生成指定范围内的随机端口
            port = MIN_PORT + random.nextInt(MAX_PORT - MIN_PORT + 1);
            // 跳过排除列表中的端口
            if (excludePorts.contains(port)) {
                continue;
            }
            // 验证端口是否未被占用
            if (isPortAvailable(port)) {
                return port;
            }
        }
    }

    private boolean isPortAvailable(int port) {
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            serverSocket.setReuseAddress(true);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

效果说明

  • 服务启动时会自动跳过exclude.ports中配置的所有端口,不会占用legacy服务的专属端口
  • 自动校验端口可用性,避免和其他已占用端口冲突
  • 支持多环境配置,不同运行环境可以单独设置不同的排除端口列表

内容的提问来源于stack exchange,提问作者BinaryBoy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 18:36:04