java Spring启动关闭钩子中途终止
我已经将ShutDownHook添加到我的Spring Boot应用程序中。当我将SIGTERM传递给我的应用程序时,shutdownhook被触发,但它在执行的中途终止。谷歌搜索了它,并尝试了许多解决方案,但它不起作用。一些专家,请在这方面帮助我
主要类别:
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);
}
}
}
我希望shutdownhook更新一些缓存和一些逻辑,这会消耗一些额外的处理时间
当我尝试使用“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.
我用shutdownhook开发了一个简单的基本java程序,并尝试使用kill-15中断。停机挂钩工作正常
# 1 楼答案
关闭时,可以添加以下代码:
@RestController
可以是其他的,比如@Component
、@SpringBootApplication
等等