简体   繁体   English

用于java Web应用程序的shutdown hook

[英]shutdown hook for java web application

I need to save some data preferrably when the java web application is stopped, or when tomcat is stopped. 当java Web应用程序停止或者tomcat停止时,我需要优先保存一些数据。 how can this be done? 如何才能做到这一点? Edit: any drawback if I use the jvm shutdown hook? 编辑:如果我使用jvm关闭钩子的任何缺点?

Use a class that implements ServletContextListener in your web.xml: 使用在web.xml中实现ServletContextListener的类:

<web-app>
    <!-- Usual stuff here -->
    <listener>
        <listener-class>com.mycompany.MyClass</listener-class>
    </listener>
</web-app>

Why do you want to do it specifically during shutdown? 为什么要在关机期间专门做? And do you really need to save it (as in "is it absolutely critical?") or would you like to (as in "would be nice but I'll live without it")? 而你真的需要将其保存(如“是绝对关键的?”),或者你 (如“将是不错,但我会没有它”)?

The distinction is important - no matter what method you try (servlet / context listener as suggested by other answers or JVM shutdown hook ) there are no guarantees that it will actually be invoked. 区别很重要 - 无论您尝试何种方法(其他答案或JVM关闭钩子建议的servlet /上下文侦听器),都无法保证实际调用它。

Servlet / context listener destroy events would only be triggered during normal (graceful) container shutdown OR during application reload. Servlet /上下文侦听器销毁事件只会在正常(正常)容器关闭期间或应用程序重新加载期间触发。 JVM shutdown hook would be triggered during process interruption as well; 在进程中断期间也会触发JVM关闭挂钩; however killing a process (or cutting out the power) would obviously trigger neither. 然而,杀死一个过程(或切断电源)显然不会触发。

As an addition to leonm's answer: 作为leonm答案的补充:

If you use Spring, you can use Spring's "lifecycle management" to achieve a similar effect. 如果使用Spring,可以使用Spring的“生命周期管理”来实现类似的效果。 For example, you can annotate a method in a bean with @PreDestroy to have it invoked automatically on container shutdown. 例如,您可以使用@PreDestroy注释bean中的方法,以便在容器关闭时自动调用它。 That way, you don't need to put anything into the web.xml . 这样,您就不需要在web.xml任何内容。

See Spring beans factory lifecycle . 请参阅Spring beans工厂生命周期

I suggest using ehcache to cache this information. 我建议使用ehcache来缓存这些信息。 If you use ehcache's persistent store, then when you start Tomcat again, the cached data will still be available. 如果您使用ehcache的持久存储,那么当您再次启动Tomcat时,缓存的数据仍然可用。

In effect, this delegates the issue to ehcache, which is optimised for these types of problems. 实际上,这会将问题委托给ehcache,后者针对这些类型的问题进行了优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM