在重新部署Java EE 7 Web应用程序时保留数据的简单方法 [英] Simple ways to keep data on redeployment of Java EE 7 web application

查看:154
本文介绍了在重新部署Java EE 7 Web应用程序时保留数据的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Java EE 7 Web服务每天生成一次统计信息,并且因为数据仅存储在ApplicationScoped bean中,所以它不会在重新部署后继续存在,因此客户端无法在下次运行完成之前检索统计信息。

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.

Java EE 7是否提供了一种简单的方法来保持应用程序状态,以便在重新部署后可用,类似于内存数据库?由于它只是一个大对象(列表),我宁愿比数据库更简单(也可能更好)。

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.

推荐答案

@ApplicationScoped bean中,您可以实现 @PreDestroy 将其保存到某个临时存储中检查并阅读 @PostConstruct 。您可以将容器管理的临时存储位置作为由 ServletContext.TEMPDIR

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.

这是使用JAXB的启动示例,以便数据以可重复使用的XML格式保存。

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

如果您碰巧部署到JBoss(WildFly),那么您也可以使用JBoss管理的数据文件夹,它比 ServletContext.TEMPDIR 所代表的位置更加永久。

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

这篇关于在重新部署Java EE 7 Web应用程序时保留数据的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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