java web应用程序的关闭钩子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1549924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
shutdown hook for java web application
提问by user121196
I need to save some data preferrably when the java web application is stopped, or when tomcat is stopped. how can this be done? Edit: any drawback if I use the jvm shutdown hook?
我需要最好在 java web 应用程序停止时或在 tomcat 停止时保存一些数据。如何才能做到这一点?编辑:如果我使用 jvm 关闭挂钩有什么缺点吗?
采纳答案by leonm
Use a class that implements ServletContextListenerin your web.xml:
使用在 web.xml中实现ServletContextListener的类:
<web-app>
<!-- Usual stuff here -->
<listener>
<listener-class>com.mycompany.MyClass</listener-class>
</listener>
</web-app>
回答by ChssPly76
Why do you want to do it specifically during shutdown? And do you really needto save it (as in "is it absolutely critical?") or would you liketo (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 guaranteesthat 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. JVM shutdown hook would be triggered during process interruption as well; however killing a process (or cutting out the power) would obviously trigger neither.
Servlet / 上下文侦听器销毁事件只会在正常(正常)容器关闭或应用程序重新加载期间触发。JVM 关闭钩子也会在进程中断时触发;然而,终止进程(或切断电源)显然不会触发两者。
回答by Steve McLeod
I suggest using ehcache to cache this information. If you use ehcache's persistent store, then when you start Tomcat again, the cached data will still be available.
我建议使用 ehcache 来缓存这些信息。如果你使用ehcache的持久化存储,那么当你再次启动Tomcat时,缓存的数据仍然可用。
In effect, this delegates the issue to ehcache, which is optimised for these types of problems.
实际上,这将问题委托给了 ehcache,它针对这些类型的问题进行了优化。
回答by sleske
As an addition to leonm's answer:
作为 leonm 答案的补充:
If you use Spring, you can use Spring's "lifecycle management" to achieve a similar effect. For example, you can annotate a method in a bean with @PreDestroy
to have it invoked automatically on container shutdown. That way, you don't need to put anything into the web.xml
.
如果使用 Spring,可以使用 Spring 的“生命周期管理”来达到类似的效果。例如,您可以在 bean 中注释一个方法,@PreDestroy
使其在容器关闭时自动调用。这样,您无需将任何内容放入web.xml
.