Simple ways to keep data on redeployment of Java EE 7 web application

主宰稳场 提交于 2019-12-20 03:02:52

问题


My Java EE 7 web service generates statistics once per day, and because data is stored only in an ApplicationScoped bean, it does not survive redeployment, so clients cannot retrieve statistics until the next run completed.

Does Java EE 7 provide a simple way to keep application state so that it will be available after redeployment, similar to an in-memory database? As it is only one big object (list), I would prefer something simpler (and maybe better performing too) than a database.


回答1:


In the @ApplicationScoped bean, you can just implement @PreDestroy to save it to some temporary storage which you then check and read in @PostConstruct. You can get the container-managed temporary storage location as a servlet context attribute keyed by ServletContext.TEMPDIR.

Here's a kickoff example using JAXB so that the data is saved in reusable XML format.

private Data data;
private File file;
private JAXBContext jaxb;

@Inject
private ServletContext servletContext;

@PostConstruct
public void init() {
    File tempdir = (File) servletContext.getAttribute(ServletContext.TEMPDIR);
    file = new File(tempdir, "data.xml");
    jaxb = JAXBContext.newInstance(Data.class);

    if (file.exists()) {
        data = (Data) jaxb.createUnmarshaller().unmarshal(file);
    }
}

@PreDestroy
public void destroy() {
    jaxb.createMarshaller().marshal(data, file);
}

If you happen to deploy to JBoss (WildFly), then you can alternatively also use JBoss-managed data folder, which is a bit more permanent than the location as represented by ServletContext.TEMPDIR.

String datadir = System.getProperty("jboss.server.data.dir");
file = new File(datadir, "data.xml");


来源:https://stackoverflow.com/questions/27804742/simple-ways-to-keep-data-on-redeployment-of-java-ee-7-web-application

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