如何通过start-stop-daemon优雅地关闭Spring Boot应用程序

Mic*_*hal 8 java multithreading start-stop-daemon spring-boot

我们有一个多线程Spring Boot应用程序,它在Linux机器上作为守护进程运行.当我尝试通过这样的start-stop-daemon停止应用程序时

start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME
Run Code Online (Sandbox Code Playgroud)

发送SIGTERM信号,应用程序即将结束.但是我希望应用程序等待,直到每个线程完成它的工作.

有没有办法,如何管理收到SIGTERM信号时会发生什么?

Evg*_*eny 15

Spring Boot应用程序向JVM注册一个关闭钩子,以确保ApplicationContext在退出时正常关闭.创建实现DisposableBean或具有@PreDestroy注释方法的bean(或bean).这个bean将在app shutdown时调用.

http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-application-exit


小智 5

@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###");
  }
}
Run Code Online (Sandbox Code Playgroud)