如何注册/添加一个自定义关闭例程,该例程将在我的Spring Boot应用程序关闭时触发?
场景:我将Spring Boot应用程序部署到Jetty servlet容器(即没有嵌入式Jetty).我的应用程序使用Logback进行日志记录,我想使用Logback的MBean JMX配置程序在运行时更改日志记录级别.其文档指出,为避免内存泄漏,在关闭时必须调用特定的LoggerContext关闭方法.
听取Spring Boot关闭事件的好方法是什么?
我试过了:
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext cac = SpringApplication.run(Example.class, args);
cac.addApplicationListener(new ApplicationListener<ContextClosedEvent>() {
@Override
public void onApplicationEvent(ContextClosedEvent event) {
logger.info("Do something");
}
});
}
Run Code Online (Sandbox Code Playgroud)
但是当应用程序关闭时,不会调用此注册的侦听器.
我试图让我的应用程序保持活动状态,以便侦听来自我的queue. 但是,一旦我的应用程序收到SIGTERM,我想确保我的应用程序很好地关闭。这意味着,在关闭之前,确保内部的作业首先完成。
阅读后,我想出了这个:
@Component
public class ParserListenerStarter {
public static void main(final String[] args) throws InterruptedException {
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(ParserReceiveJmsContext.class);
context.registerShutdownHook();
System.out.println("Listening...");
Runtime.getRuntime().addShutdownHook( //
new Thread() {
@Override
public void run() {
System.out.println("Closing parser listener gracefully!");
context.close();
}
});
while (true) {
Thread.sleep(1000);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后我向kill我的应用程序发送一个命令;这是我的输出:
Listening...
// output from my other beans here
Closing parser listener gracefully!
Process finished with exit code 143 (interrupted by signal …Run Code Online (Sandbox Code Playgroud)