|
springboot中判断服务器某个端口是否被占用主要功能:
检查指定端口是否被占用
自动查找可用端口
支持在应用启动时动态切换端口
提供日志输出
你可以根据实际需求:
修改端口检查的超时时间
添加重试机制
自定义端口范围
增加更详细的错误处理
在 SpringBoot 中检查端口占用有几种方法。下面是一个工具类的实现:
- import java.io.IOException;
- import java.net.Socket;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class PortUtils {
- private static final Logger logger = LoggerFactory.getLogger(PortUtils.class);
- /**
- * 检查指定的端口是否被占用
- * @param host 主机地址
- * @param port 端口号
- * @return true:端口已占用 false:端口未占用
- */
- public static boolean isPortInUse(String host, int port) {
- boolean isInUse = false;
- try (Socket socket = new Socket(host, port)) {
- // 如果能成功创建Socket,说明端口已被占用
- isInUse = true;
- logger.info("Port {} is in use", port);
- } catch (IOException e) {
- // 如果创建Socket失败,说明端口未被占用
- isInUse = false;
- logger.info("Port {} is not in use", port);
- }
- return isInUse;
- }
- /**
- * 获取可用的端口号
- * @param startPort 起始端口号
- * @return 可用的端口号,如果没有找到返回-1
- */
- public static int findAvailablePort(int startPort) {
- int maxPort = 65535;
- for (int port = startPort; port <= maxPort; port++) {
- if (!isPortInUse("localhost", port)) {
- return port;
- }
- }
- return -1;
- }
- }
复制代码 使用示例:
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import com.example.utils.PortUtils;
- @SpringBootApplication
- public class Application {
- public static void main(String[] args) {
- int port = 8080;
-
- // 检查端口是否被占用
- if (PortUtils.isPortInUse("localhost", port)) {
- // 如果端口被占用,寻找新的可用端口
- int newPort = PortUtils.findAvailablePort(port + 1);
- if (newPort != -1) {
- System.setProperty("server.port", String.valueOf(newPort));
- System.out.println("Port " + port + " is in use, using port " + newPort + " instead");
- } else {
- throw new RuntimeException("No available port found");
- }
- }
- SpringApplication.run(Application.class, args);
- }
- }
复制代码 也可以在配置类中使用:
- import org.springframework.boot.web.server.WebServerFactoryCustomizer;
- import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
- import org.springframework.context.annotation.Configuration;
- import com.example.utils.PortUtils;
- @Configuration
- public class ServerConfig implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
- @Override
- public void customize(ConfigurableServletWebServerFactory factory) {
- int port = factory.getPort();
- if (PortUtils.isPortInUse("localhost", port)) {
- int newPort = PortUtils.findAvailablePort(port + 1);
- if (newPort != -1) {
- factory.setPort(newPort);
- } else {
- throw new RuntimeException("No available port found");
- }
- }
- }
- }
复制代码
|
|