Java Web 应用程序的关闭钩子

发布于 2024-08-08 06:04:17 字数 87 浏览 6 评论 0原文

我需要在 java web 应用程序停止或 tomcat 停止时保存一些数据。这怎么办? 编辑: 如果我使用 jvm shutdown hook 有什么缺点吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

两人的回忆 2024-08-15 06:04:17

在 web.xml 中使用实现 ServletContextListener 的类:

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

Use a class that implements ServletContextListener in your web.xml:

<web-app>
    <!-- Usual stuff here -->
    <listener>
        <listener-class>com.mycompany.MyClass</listener-class>
    </listener>
</web-app>
樱娆 2024-08-15 06:04:17

为什么要在关机期间专门这样做呢?你真的需要保存它(如“这绝对重要吗?”)或者你愿意(如“会很好,但我会活下去”)没有它”)?

区别很重要 - 无论您尝试什么方法(servlet /上下文侦听器如其他答案或 JVM 关闭挂钩不能保证它实际上会被调用。

Servlet/上下文侦听器销毁事件只会在正常(正常)容器关闭期间或应用程序重新加载期间触发。进程中断时也会触发 JVM shutdown hook;然而,杀死一个进程(或切断电源)显然不会触发这两者。

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.

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.

孤单情人 2024-08-15 06:04:17

作为leonm的回答的补充:

如果你使用Spring,你可以使用Spring的“生命周期管理”来达到类似的效果。例如,您可以使用 @PreDestroy 注释 bean 中的方法,以便在容器关闭时自动调用该方法。这样,您无需将任何内容放入 web.xml 中。

请参阅 Spring beans 工厂生命周期< /a>.

As an addition to leonm's answer:

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.

See Spring beans factory lifecycle.

笑饮青盏花 2024-08-15 06:04:17

我建议使用ehcache来缓存这些信息。如果你使用ehcache的持久化存储,那么当你再次启动Tomcat时,缓存的数据仍然可用。

实际上,这将问题委托给了 ehcache,它针对这些类型的问题进行了优化。

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.

In effect, this delegates the issue to ehcache, which is optimised for these types of problems.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文