Jax rs:如何在每次服务器重新启动时自动运行方法? [英] Jax rs: How can I run a method automatically everytime my server restarts?

查看:113
本文介绍了Jax rs:如何在每次服务器重新启动时自动运行方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经制作了一个jax rs jersey Web服务.服务器重新启动时,我必须从数据库加载数据.我现在正在做的就是将此网址称为

I Have made a jax rs jersey web service. I have to load data from database when server restarts. What I am doing now is calling this url

http://localhost:8080/jersey-openshift-quickstart2/logisure/load

它从数据库加载数据,并通过调用线程每20秒进行一次更新.基于此数据,其他API功能也可以工作.现在,当我将其部署到云中时,我发现服务器每2-3天就会重启一次,因此我需要我的Web服务自动调用

It loads data from database and keeps on updating it in every 20 sec by calling a thread. Based on this data other API functionalities work. Now when I deployed it on cloud I found out server restarts in every 2-3 days so I need my webservice to automatically call

http://localhost:8080/jersey-openshift-quickstart2/logisure/load

服务器重新启动时.我该怎么办?

when my server restarts. How can i do it?

推荐答案

您可以编写一个ServletContextListener,它从contextInitialized()方法中调用您的方法.您将监听器附加到web.xml中的webapp,例如

You can write a ServletContextListener which calls your method from the contextInitialized() method. You attach the listener to your webapp in web.xml, e.g.

<listener>
   <listener-class>listeners.MyListener</listener-class>
</listener>

或者,如果您使用Java配置而不是web.xml,则可以使用Java代码进行等效操作.

Or if you are using a Java config instead of web.xml, you do the equivalent with Java code.

这是您的上下文侦听器的代码:

And here's the code for your context listener:

package listeners;

public class MyListener implements javax.servlet.ServletContextListener {

   public void contextInitialized(ServletContext context) {
      //load data here
   }
}

这将在任何Servlet容器和任何框架上运行(您不依赖Jersey).

This will work on whatever Servlet container and with whatever framework (you don't depend on Jersey).

这篇关于Jax rs:如何在每次服务器重新启动时自动运行方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆