作用
- 对于有多个服务的项目,各服务改为随机端口启动,这样就不需要每次启动要先关掉老版本的服务,可以用新端口直接启动,新版本启动成功后再停掉老版本。
- Being able to use dynamic port would be nice, if one wants to run multiple instances of a service locally without having to create multiple configurations of it (i.e. just relaunch the same thing a few times and have each running instance dynamically pick a port).
方法
根据官方文档的建议,配置端口为0(server.port=0),可以给容器分配一个未被占用的随机端口号
https://docs.spring.io/spring-boot/docs/1.5.9.RELEASE/reference/htmlsingle/#howto-user-a-random-unassigned-http-port
具体的做法(参考https://www.onlinetutorialspoint.com/spring-boot/how-to-change-spring-boot-tomcat-port-number.html):
- updating the application.properties file
application.properties
server.port=0
- configuring the Embedded Servlet Container
package com.onlinetutorialspoint.spring.boot;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.stereotype.Component;
@Component
public class CustomContainer implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(0);
}
}
- passing the arguments while running the application
java -Dserver.port=0 Application