如何从代码中重新启动springboot应用程序



我有一个带有嵌入式tomcat的springboot应用程序。在某些情况下,它应该从代码中重新启动。

我已经阅读了几篇关于这方面的文章和SO帖子,但还没有找到一个干净的解决方案
我知道"context.close"、"SpringApplication.exet(context("存在,并且可以被包装成这样的东西:

public static void restart() {
ApplicationArguments args = context.getBean(ApplicationArguments.class);
Thread thread = new Thread(() -> {
context.close();
context = SpringApplication.run(Application.class, args.getSourceArgs());
});
thread.setDaemon(false);
thread.start();
}

:https://www.baeldung.com/java-restart-spring-boot-app

问题是,使用context.close((并不能以一种干净的方式工作
虽然上下文本身将被重新启动,但一堆线程将留在后台(如Thread[pool-3-Thread-1,5,main]Thread[Signal Dispatcher,9,system]Thread[OkHttp TaskRunner,5,main]等(。
每次上下文重新启动时,这些线程都会被重新创建,因此每次重新启动时线程数量会逐渐增加。随着时间的推移,导致线程混乱。

注意1:使用'context.close(('的简单应用程序退出也不起作用,因为存在这些遗留线程。因此上下文关闭甚至不会关闭应用程序。

注意2:如果我使用System.exit(SpringApplication.ext(context((,我可以优雅地终止应用程序,但无法重新启动。

注意3:我既不想使用devtools也不想使用actuator

因此,问题是如何对springboot应用程序执行完全重新启动?

您可以在spring-cloudcontext依赖项中使用RestartEndPoint以编程方式重新启动spring Boot应用程序:

@Autowired
private RestartEndpoint restartEndpoint;

...

Thread restartThread = new Thread(() -> restartEndpoint.restart());
restartThread.setDaemon(false);
restartThread.start();

最新更新