Spring Boot Shutdown Hook终止中途

时间:2018-04-13 12:51:48

标签: java spring-boot shutdown-hook

我已将ShutDownHook添加到我的Spring Boot应用程序中。当我将SIGTERM传递给我的应用程序时,关闭钩子被触发但它在中途终止,即在执行中间。用Google搜索并尝试了许多无法解决的解决方案。有些专家,请帮帮我。

主类:

ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(MyApp.class)
            .profiles("default")
            .registerShutdownHook(false)
            .build()
            .run(args);
    Runtime.getRuntime().addShutdownHook(new Thread(new GracefulShutdownHook(applicationContext)));

GracefulShutdownHook类:

public class GracefulShutdownHook implements Runnable {
    private final ConfigurableApplicationContext applicationContext;

    public GracefulShutdownHook(ConfigurableApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void run() {
        try {
            log.info("Gonna wait for 5 seconds before shutdown SpringContext!");
            Thread.sleep(5 * 1000);
            log.info("Spring Application context starting to shutdown");
            applicationContext.close();
            log.info("Spring Application context is shutdown");
        } catch (InterruptedException e) {
            log.error("Error while gracefulshutdown Thread.sleep", e);
        }
    }
}

我希望shutdown hook更新一些缓存以及一些消耗一些额外处理时间的逻辑。

当我尝试使用'kill -15'杀死时记录:

Apr 13 10:08:22 ssed java[14354]: 2018-04-13T10:08:22,778 INFO  [c.o.GracefulShutdownHook] -- Gonna wait for 10 seconds before shutdown SpringContext!

我正在使用嵌入式Jetty服务器。我还启用了Jetty日志,但只有在关机时才打印日志。我的期望是applicationContext.close()应在10秒睡眠后调用,但线程在10秒后没有恢复。

当我尝试停止使用systemctl时,请找到以下日志。

Apr 12 15:24:51 vm33 systemd[1]: Stopping Session Application Service...
Apr 12 15:24:51 vm33 java[29538]: 2018-04-12T15:24:51,421 INFO  [c.o.GracefulShutdownHook] -- Gonna wait for 10 seconds before shutdown SpringContext!
Apr 12 15:25:01 vm33 systemd[1]: Stopped Session Application Service.

我使用shutdown hook开发了一个简单的基本java程序,并尝试使用'kill -15'进行中断。关机挂钩工作正常。

1 个答案:

答案 0 :(得分:0)

您可以添加以下代码以在关机时执行操作:

@RestController
@Slf4j
public class GetDataController {

  //your code

  @PreDestroy
  public void onExit() {
    log.info("###STOPing controller ##");
    try {
      Thread.sleep(5 * 1000);
    } catch (InterruptedException e) {
      log.error("", e);;
    }
    log.info("###STOP FROM THE LIFECYCLE controller###");
  }
}

@RestController可能与@Component@SpringBootApplication等类似,依此类推。