Spring项目配置随机端口号

作用

  1. 对于有多个服务的项目,各服务改为随机端口启动,这样就不需要每次启动要先关掉老版本的服务,可以用新端口直接启动,新版本启动成功后再停掉老版本。
  2. 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 {@Overridepublic void customize(ConfigurableEmbeddedServletContainer container) {container.setPort(0);}
}
  • passing the arguments while running the application
java -Dserver.port=0 Application


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部