how to re-initialize java servlet on text file change

杀马特。学长 韩版系。学妹 提交于 2019-12-05 03:01:37

问题


I have a servlet that pulls data from a text file during initialization. Now I am updating that text file with a cron job(say everyday at 10am) and want to reinitialize the servlet every time this particular file changes.

Second approach I can follow is to sync the reinitialization of the servlet to my cron job.

Kindly suggest on how to go about implementing either of the above two approaches.

thanks.


回答1:


Don't get hold of it as instance variable of the servlet. Create a ServletContextListener which stores it in the application scope and runs a thread which updates it on every interval with help of ScheduledExecutorService.

E.g.

@WebListener
public class Config implements ServletContextListener {

    private ScheduledExecutorService scheduler;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        Data data = new Data(); // Your class which reads and holds data upon construction.
        event.getServletContext().setAttribute("data", data);
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Reloader(data), 0, 1, TimeUnit.DAYS);
    }

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

}

with this runnable

public class Reloader implements Runnable {

    private Data data;

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

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

}

It's accessible a random servlet.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    Data data = (Data) getServletContext().getAttribute("data");
    // ...
}

And even in a random JSP.

${data.something}



回答2:


Have your servlet occasionally check the file for changes with a timer.

Googling "Java monitor file for changes" will present many examples, one of which you can find here: http://www.devdaily.com/java/jwarehouse/jforum/src/net/jforum/util/FileMonitor.java.shtml



来源:https://stackoverflow.com/questions/5428130/how-to-re-initialize-java-servlet-on-text-file-change

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