每月重新加载一次servlet [英] reload servlet once a month

查看:144
本文介绍了每月重新加载一次servlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何每月重新加载一次servlet?

How can a reload a servlet once a month?

我们得到的一些数据会每月更改一次,数据是针对servlet的,但我们不知道需要将数据保存到数据库中,而我们想让它成为一个配置文件,每月更换一次,我该怎么做?

We got some data which will change once a month, the data is for the servlet, but we don't need to save the data into DB, instead we want to make it a configuration file which will be replaced once a month, how can I do this?

我知道servlet的生命周期策略由容器控制,我使用的是websphere 7,但我不知道是否有办法在websphere中配置它。

I know that the servlet's lifecycle policy is controlled by the container, I am using websphere 7, but I don't know if there is a way to configure that in websphere.

将调用destory()方法会影响servlet的运行实例吗? AFAIK,servlet是多线程的。

Will calling the destory() method affect the running instances of servlet? AFAIK, the servlet is multi-threaded.

推荐答案

不要使用servlet来存储数据。而是将数据存储为 ServletContext 的属性。您可以借助 ServletContextListener来完成 。在 ScheduledExecutorService

Don't use a servlet to store the data. Rather store the data as an attribute of the ServletContext. You can do it with help of a ServletContextListener. The very same listener class can also be used to reload the data at timed intervals with help of ScheduledExecutorService.

这是一个启动示例:

public class Config implements ServletContextListener {

    private ScheduledExecutorService scheduler;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        Data data = new Data();
        event.getServletContext().setAttribute("data", data);
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Reloader(data), 0, 30, TimeUnit.DAYS);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        scheduler.shutdownNow();
    }

}

(请注意,有没有 TimeUnit.MONTH ,所以这是每月一次的最佳选择。)

(note that there's no TimeUnit.MONTH, so this is the best you can get for "once a month")

Reloader 类看起来像这样:

public class Reloader implements Runnable {

    private Data data;

    public Reloader(Data data) {
        this.data = data;
    }

    @Override
    public void run() {
        data.reload();
    }

}

在<$中注册监听器后c $ c> /WEB-INF/web.xml 如下

<listener>
    <listener-class>com.example.Config</listener-class>
</listener>

它将创建数据实例和a每30天执行 data.reload()的单线程调度程序,您可以访问每个servlet中的 Data 实例如下:

it will create the Data instance and a single thread scheduler which executes the data.reload() every 30 days and you can access the Data instance in every servlet as follows:

Data data = (Data) getServletContext().getAttribute("data");

在JSP中如下:

${data}

这篇关于每月重新加载一次servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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