java 如何通过 start-stop-daemon 优雅地关闭 Spring Boot 应用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36691355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to gracefuly shutdown a Spring Boot application by start-stop-daemon
提问by Michal
We have a multithreaded Spring Boot Application, which runs on Linux machine as a daemon. When I try to stop the application by start-stop-daemon like this
我们有一个多线程 Spring Boot 应用程序,它作为守护进程在 Linux 机器上运行。当我尝试像这样通过 start-stop-daemon 停止应用程序时
start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME
The SIGTERM signal is sent and application immetiately ends. However I want the application to wait, until every thread finishes it's work.
发送 SIGTERM 信号,应用程序立即结束。但是我希望应用程序等待,直到每个线程完成它的工作。
Is there any way, how to manage what happens, when SIGTERM signal is received?
有什么办法,当收到 SIGTERM 信号时,如何管理会发生什么?
回答by Evgeny
Spring Boot app registers a shutdown hook with the JVM to ensure that the ApplicationContext
is closed gracefully on exit. Create bean (or beans) that implements DisposableBean
or has method with @PreDestroy
annotation. This bean will be invoked on app shutdown.
Spring Boot 应用程序向 JVM 注册了一个关闭钩子,以确保ApplicationContext
在退出时正常关闭。创建实现DisposableBean
或具有带@PreDestroy
注释的方法的bean(或 bean)。此 bean 将在应用程序关闭时调用。
回答by lizhipeng
sample as mentioned by @Evgeny
@Evgeny 提到的样本
@SpringBootApplication
@Slf4j
public class SpringBootShutdownHookApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootShutdownHookApplication.class, args);
}
@PreDestroy
public void onExit() {
log.info("###STOPing###");
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
log.error("", e);;
}
log.info("###STOP FROM THE LIFECYCLE###");
}
}