Spring Boot 关闭钩子 [英] Spring Boot shutdown hook

查看:40
本文介绍了Spring Boot 关闭钩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何注册/添加在 Spring Boot 应用程序关闭时应触发的自定义关闭例程?

How can I register/add a custom shutdown routine that shall fire when my Spring Boot application shuts down?

场景:我将 Spring Boot 应用程序部署到 Jetty servlet 容器(即,没有嵌入式 Jetty).我的应用程序使用 Logback 进行日志记录,我想在运行时使用 Logback 的 MBean JMX 配置器更改日志记录级别.其文档指出,为了避免内存泄漏,在关闭时必须调用特定的 LoggerContext 关闭方法.

Scenario: I deploy my Spring Boot application to a Jetty servlet container (i.e., no embedded Jetty). My application uses Logback for logging, and I want to change logging levels during runtime using Logback's MBean JMX configurator. Its documentation states that to avoid memory leaks, on shutdown a specific LoggerContext shutdown method has to be called.

监听 Spring Boot 关机事件的好方法是什么?

What are good ways to listen on Spring Boot shutdown events?

我已经尝试过:

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");
        }
    });
}

但是当应用程序关闭时,这个注册的监听器不会被调用.

but this registered listener does not get called when the application shuts down.

推荐答案

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

每个 SpringApplication 都会向 JVM 注册一个关闭钩子,以确保 ApplicationContext 在退出时正常关闭.可以使用所有标准的 Spring 生命周期回调(例如 DisposableBean 接口或 @PreDestroy 注解).

Each SpringApplication will register a shutdown hook with the JVM to ensure that the ApplicationContext is closed gracefully on exit. All the standard Spring lifecycle callbacks (such as the DisposableBean interface, or the @PreDestroy annotation) can be used.

此外,如果 bean 希望在应用程序结束时返回特定的退出代码,它们可以实现 org.springframework.boot.ExitCodeGenerator 接口.

In addition, beans may implement the org.springframework.boot.ExitCodeGenerator interface if they wish to return a specific exit code when the application ends.

这篇关于Spring Boot 关闭钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆