【问题标题】:How to close Spring beans properly after received a SIGTERM?收到 SIGTERM 后如何正确关闭 Spring bean?
【发布时间】:2016-11-18 20:29:30
【问题描述】:

我正在尝试保持我的应用程序活动,以便收听来自我的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);
        }
    }

}

然后我向我的应用程序发送kill 命令;这是我的输出:

Listening...
// output from my other beans here
Closing parser listener gracefully!

Process finished with exit code 143 (interrupted by signal 15: SIGTERM)

我的 bean 中的 shutdown 方法没有被调用:

@PreDestroy public void shutdown() {..}

我不是Spring 方面的专家,所以对于我在这里遗漏的任何愚蠢观点,我深表歉意。

我怎样才能shutdown我的bean然后很好地关闭我的应用程序?

【问题讨论】:

    标签: java spring


    【解决方案1】:

    所有你需要的:

    context.registerShutdownHook();
    

    所以,添加上面的代码,然后您的 @PreDestroy 方法将被调用。 之后,您无需执行任何其他操作。这意味着你必须删除

     Runtime.getRuntime().addShutdownHook( //
                new Thread() {
                    @Override
                    public void run() {
                        System.out.println("Closing parser listener gracefully!");
                        context.close();
                    }
                });
    

    当你添加这个时,你替换了 Spring 钩子,它会破坏 bean,因为在内部,方法看起来像

    if (this.shutdownHook == null) {
            // No shutdown hook registered yet.
            this.shutdownHook = new Thread() {
                @Override
                public void run() {
                    doClose();
                }
            };
            Runtime.getRuntime().addShutdownHook(this.shutdownHook);
        }
    

    【讨论】:

    • 你说得对,尼古拉!非常感谢您的回答!
    猜你喜欢
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 2015-05-24
    • 2021-06-23
    • 1970-01-01
    • 2019-06-09
    • 1970-01-01
    相关资源
    最近更新 更多