通过ApplicationListener保存缓存数据

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext

ctx.registerShutdownHook();

ctx.addApplicationListener(new ApplicationListener<ContextClosedEvent>() {

@Override

public void onApplicationEvent(ContextClosedEvent event) {

ServerTask task = (ServerTask) ctx.getBean("serverTask");

task.exit();

logger.error("系统关闭成功");

}

});

一开始使用destroy方法想通过这个来监听jvm 关闭事件,但是destroy方法之间是没有优先级的,所以无法处理。

通过这种监听ContextClosedEvent事件来保存缓存中的数据

这种方法只对于kill -15 方式结束进程有效,kill -9就别想了。

当然对于保存缓存数据最好通过其他方式,避免误操作。例如轮训配置文件等等。。。

猜你喜欢

转载自freyja.iteye.com/blog/1553411