Spring Boot 以编程方式重启应用 [英] Spring Boot programmatically restart app

查看:55
本文介绍了Spring Boot 以编程方式重启应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Spring Boot 应用程序,我需要在其中编写 Java 代码来关闭应用程序本身(包括它的线程),然后重新启动它.我尝试了以下两种方法,第一种是在 Java 中发出 Linux 命令,如下所示:

I'm developing a Spring Boot app, in which I need to write Java code to shut down the app itself (including its threads), and then restart it. I've tried the following two methods, the first one is to issue a Linux command in Java like the following:

Process p = Runtime.getRuntime().exec("kill -SIGINT " + pid);

其中 pid 是应用程序本身的 pid.这与按 "ctrl + c" 具有相同的效果.但是以这种方式成功关闭应用程序后,我不知道如何重新启动它.我尝试使用相同的方法发出另一个命令(例如mvn spring-boot:run",这是我启动应用程序的方式),但由于应用程序已关闭,因此这不起作用.

where pid is that of the app itself. This has the same effect as pressing "ctrl + c". But having shut down the app successfully this way, I don't know how I can restart it. I tried to issue another command (like "mvn spring-boot:run", which is how I start the app) using the same method but since the app is shut down already, this doesn't work.

其次,我还尝试调用 AbstractApplicationContext 的 refresh() 方法,如下所示:

Secondly, I've also tried calling the refresh() method of AbstractApplicationContext as follows:

AbstractApplicationContext appContext = new AnnotationConfigApplicationContext();
appContext.registerShutdownHook();
appContext.refresh();

但是我觉得这种上下文刷新和重启不一样?

But I don't think this kind of context refreshing is the same as restarting?

那么用 Java 代码重新启动 Spring Boot 应用程序的正确方法是什么?感谢任何帮助,谢谢!

So what is the proper way to restart a Spring Boot app with Java code? Any help is appreciated, thanks!

推荐答案

gstackoverflow 的答案对我不起作用,我的解决方案:

The gstackoverflow's answer didn't work for me, my solution:

为 build.gradle 添加依赖

Add dependencies to build.gradle

compile group: 'org.springframework.cloud', name: 'spring-cloud-starter', version: '2.0.0.RELEASE'
compile("org.springframework.boot:spring-boot-starter-actuator")

自动连线重启端点

@Autowired
private RestartEndpoint restartEndpoint;

将此添加到 application.properties

Add this to application.properties

management.endpoint.restart.enabled = true

并调用

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

这篇关于Spring Boot 以编程方式重启应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆