Spring Boot以编程方式重启app

时间:2017-07-13 07:45:07

标签: java spring spring-boot

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

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

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

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

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

但我不认为这种上下文刷新与重启相同吗?

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

6 个答案:

答案 0 :(得分:2)

您需要向应用程序添加#define F(x) (x)^3-2.5(x)^2-1.8(x)+2.356spring-boot-starter-actuator个依赖项,并使用Spring cloud端点重新启动应用程序。 Here是文档:

  

对于Spring Boot Actuator应用程序,有一些   其他管理端点:

     
      
  • POST到/ env以更新环境并重新绑定   @ConfigurationProperties和日志级别

  •   
  • / refresh用于重新加载启动带上下文并刷新   @RefreshScope豆

  •   
  • / restart以关闭ApplicationContext并重新启动它   (默认禁用)

  •   
  • / pause和/ resume用于调用Lifecycle方法(stop()和   ApplicationContext上的start())

  •   

完成后,您可以使用/restart来重新启动应用程序(通过REST APIRestTemplate)。这将是更清洁的方式来重新启动应用程序,而不是杀死它并重新运行它。

答案 1 :(得分:1)

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

将依赖项添加到build.gradle

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

自动连线的RestartEndpoint

@Autowired
private RestartEndpoint restartEndpoint;

将此添加到application.properties

management.endpoint.restart.enabled = true

然后调用

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

答案 2 :(得分:0)

执行已经准备好的脚本/程序,而不是仅执行kill命令,该脚本/程序会终止调用进程并启动应用程序的新实例。

答案 3 :(得分:0)

DevTools依赖应用程序上下文的关闭挂钩在重启期间关闭它。如果您通过SpringApplication.setRegisterShutdownHook(false)禁用了关机挂钩,它将无法正常工作。

另见:Using Spring Boot

答案 4 :(得分:0)

除了Darshan Mehta回答:

就我而言,我这样做了:

1.added dependecies:

compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.cloud:spring-cloud-starter:1.2.4.RELEASE")

2.autowired restartEndpoint:

import org.springframework.cloud.context.restart.RestartEndpoint;
....
@Autowired
private RestartEndpoint restartEndpoint;

第3。并调用:

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        restartEndpoint.invoke();
    }
});
thread.setDaemon(false);
thread.start();

我需要新的Thread,因为spring mvc为每个请求创建守护进程线程

答案 5 :(得分:0)

我们可以像这样使用Spring Devtools的Restarter:

org.springframework.boot.devtools.restart.Restarter.getInstance().restart()
相关问题