1. 下载ehcache的相关jar文件并放置到Java Web工程的WebRoot/WEB-INF/lib目录下;
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"
/>
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
@Entity
public class Question implements Serializable{
}
5. 在执行查询的query语句上设置cacheable属性,以便将查询结果存入缓存:
6.defaultCache 的解释
<defaultCache maxElementsInMemory="500000" eternal="false"
timeToIdleSeconds="1800" timeToLiveSeconds="1800"
overflowToDisk="true" diskPersistent="true">
<cacheEventListenerFactory
class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory"
properties="replicateAsynchronously=true, replicatePuts=true,
replicateUpdates=true, replicateUpdatesViaCopy=false,
replicateRemovals=true" />
</defaultCache>
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"
diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000"
diskPersistent="false" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<cacheEventListenerFactory
class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory"
properties="replicateAsynchronously=true, replicatePuts=true,
replicateUpdates=true, replicateUpdatesViaCopy=false,
replicateRemovals=true" />
</defaultCache>
defaultCache 默认缓存,有些没有被配置的缓存对象将使用默认缓存
maxElementsInMemory 内存中最大缓存对象数.当超过最大对象数的时候,ehcache会按指定的策略去清理内存
eternal 缓存对象是否永久有效,一但设置了,timeout将不起作用.
timeToIdleSeconds 设置Element在失效前的允许闲置时间.仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大.
timeToLiveSeconds timeToLiveSeconds:设置Element在失效前允许存活时间.最大时间介于创建时间和失效时间之间.仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大.
overflowToDisk 配置此属性,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中.
diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区.
maxElementsOnDisk 磁盘中最大缓存对象数,若是0表示无穷大.
diskPersistent 是否在重启服务的时候清楚磁盘上的缓存数据.true不清除.
diskExpiryThreadIntervalSeconds 磁盘失效线程运行时间间隔.
memoryStoreEvictionPolicy memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存.默认策略是LRU(最近最少使用).你可以设置为FIFO(先进先出)或是LFU(较少使用).
注:普通cache同defaultCache的属性一样,可以根据自己的实际需求去配置