ehcache简单使用

项目中需要实现一个功能,定时查询FTP服务器某个目录下的文件,并及时下载至本机,同时不能消耗太多系统资源。
最后实现是使用ehcache,将文件路径和文件大小缓存,如果前后两次无变化,则忽略。如果同一路径大小有变化,则下载此文件。
当然,由于缓存的不可靠近,如果数据库可以支持,可以将数据写入表中,对数值进行标记。这样更加可靠。
以下是ehcache的简单应用。

1、下载ehcache的相关jar文件并放置到Java Web工程的WebRoot/WEB-INF/lib目录下;
SSH架构下ehcache缓存模块的配置使用
2、编辑JPA配置文件 persistence.xml:

<property name="hibernate.cache.provider_class" value="net.sf.ehcache.hibernate.SingletonEhCacheProvider"/>       
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>

3、将ehcache的配置文件ehcache.xml放置在Java Web工程的src目录下,并根据自身需要进行类似如下的配置:

<cache name="edu.bupt.laaip.model.Question"
    maxElementsInMemory="500"
    eternal="false"
    timeToIdleSeconds="1800"
    timeToLiveSeconds="3600"
    overflowToDisk="false"
/>

4、在你想要添加缓存的JPA实体类上添加标签如下:

package edu.bupt.laaip.model;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Entity
public class Question implements Serializable{

    ……
}

5、在执行查询的query语句上设置cacheable属性,以便将查询结果存入缓存:

  @SuppressWarnings("unchecked")
    @Override
    public List getAll() {
       // TODO Auto-generated method stub
       Query query = getEntityManager().createQuery("select q FROM Question q");
       query.setHint("org.hibernate.cacheable", true);
       return query.getResultList();
    }

参考链接:
http://blog.sina.com.cn/s/blog_6826662b01017tgg.html

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/alfily/p/4657226.html