SpringBoot 防止“端口正在使用”

我正在使用 Spring Boot,我想知道是否有定义的方法或一些开源库来确保连接建立的安全。

例如默认端口是 8080,所以如果端口已经在使用,我会将端口设置为 8081,而不是让应用程序启动失败。


Smart猫小萌
浏览 265回答 2
2回答

慕的地10843

添加到您的属性文件server.port=0,spring boot 将自动选择可用端口。请参阅文档(第 75.7 节 - 这是解决您的问题的一个很好的例子)。

holdtom

我只是让你重新考虑这个想法,它不是生产就绪的,需要一些改进,但你绝对可以在你的main方法中尝试这样的事情:@SpringBootApplicationpublic class MyApplication {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; SpringApplication app = new SpringApplication(MyApplication.class);&nbsp; &nbsp; &nbsp; &nbsp; int serverPort = 8080;&nbsp; &nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; app.setDefaultProperties( Collections.singletonMap( "server.port", Integer.toString(serverPort) ) );&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; app.run(args);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; serverPort++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; } while (serverPort < 9000);&nbsp; &nbsp; }}您可能已经注意到,理论上这应该会尝试一次又一次地设置端口,以防出现错误。我将其限制为端口 9000,但您可以尝试修补一个更适合您打算执行的操作的解决方案,并在您的特定用例场景中对其进行调整。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java