reload servlet once a month

ぐ巨炮叔叔 提交于 2019-12-05 05:04:00

问题


How can a reload a servlet once a month?

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?

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.

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


回答1:


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.

Here's a kickoff example:

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();
    }

}

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

Where the Reloader class look like this:

public class Reloader implements Runnable {

    private Data data;

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

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

}

After registering the listener in /WEB-INF/web.xml as follows

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

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");

and in JSPs as follows:

${data}


来源:https://stackoverflow.com/questions/5798688/reload-servlet-once-a-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!