2016-07-15 105 views
0

我试图保留我的应用程序存活以便倾听从我的queue的一些消息。但是,一旦我的应用程序收到SIGTERM,我想确保我的应用程序很好地关闭。这意味着,确保内部工作在关闭之前先完成。如何在收到SIGTERM后正确关闭Spring Bean?

阅读之后,我想出了这个:

@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) 

从我的豆子的shutdown方法还不能称作:

@PreDestroy public void shutdown() {..} 

我不是Spring的专家,所以我现在没有任何愚蠢的一点遗憾的是,我在这里失踪了。

我怎么能shutdown我的豆,然后关闭我的应用程序很好?

回答

1

所有你需要:

context.registerShutdownHook(); 

因此,添加上面的代码,然后你的@PreDestroy方法将被调用。 之后,你不需要做任何事情。这意味着你必须删除

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

当你加入这个,你更换了弹簧钩,该做的豆销毁,因为在内部,方法看起来像

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

你说得对尼古拉!非常感谢您的回答! –