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

查看:1887
本文介绍了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.

推荐答案

http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-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天全站免登陆