Spring Boot自动更改端口,如果端口已被使用

3

我正在使用Windows命令来运行我的Spring Boot应用程序,并嵌入Tomcat。此外,我需要使用CommandlineRunner运行许多控制台应用程序。当然,我遇到了端口已被占用的问题。

***************************
APPLICATION FAILED TO START
***************************
Description:
Web server failed to start. Port 8080 was already in use.
Action:
Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.

我可以在每个控制台应用程序中设置端口,但我需要同时运行至少10个控制台应用程序。

是否有任何配置或解决方案,使应用程序能够自动更改端口?

1个回答

2
您可以自动生成端口号以解决“端口已被占用”的问题。只需在属性或yml中输入“server.port = 0”。它会自动生成服务器端口,并在控制台中显示。 application.properties
server.port= 0

application.yml

server:
  port : 0

控制台

enter image description here


很好,謝謝!我也能控制自動生成的端口安裝嗎?比如說,如果8080被占用了,能不能改成8081之類的? - Fanny
不行,因为端口是来自于TCP/IP模块。 - Faheem azaz Bhanej
它会被你的IDE自动处理。 - Faheem azaz Bhanej
那么当我使用“java -jar”运行它时,JRE属性会自动处理它? - Fanny
Spring Boot web 中定义服务器端口,并由 IDE(Eclipse、Netbeans、IntelliJ) 处理,而不是由 Java 运行环境 处理。 - Faheem azaz Bhanej

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接