Ehcache在很多项目中都出现过,用法也比较简单。一般的加些配置就可以了,而且Ehcache可以对页面、对象、数据进行缓存,同时支持集群/分布式缓存。如果整合Spring、Hibernate也非常的简单,Spring对Ehcache的支持也非常好。EHCache支持内存和磁盘的缓存,支持LRU、LFU和FIFO多种淘汰算法,支持分布式的Cache,可以作为Hibernate的缓存插件。同时它也能提供基于Filter的Cache,该Filter可以缓存响应的内容并采用Gzip压缩提高响应速度。
一、准备工作
导入如下包:ehcache ;commons-logging ; cglib ; asm ; spring的jar包;struts2的jar包
二、添加spring配置文件applicationContext-cache.xml
<?xml version="1.0"encoding="UTF-8"?>
<beansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!--缓存 -->
<bean id="cacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<propertyname="configLocation">
<value>classpath:ehcache.xml</value>
</property>
</bean>
<bean id="userCache"class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<ref local="cacheManager" />
</property>
<property name="cacheName" value="userCache"/>
</bean>
</beans>
三、添加EhCache配置文件ehcache.xml
<?xml version="1.0"encoding="UTF-8"?>
<ehcache>
<!-- maxElementsInMemory设定内存中创建对象的最大值-->
<!-- eternal设置元素(译注:内存中对象)是否永久驻留。如果是,将忽略超时限制且元素永不消亡-->
<!-- overflowToDisk设置当内存中缓存达到 maxInMemory限制时元素是否可写到磁盘上 -->
<!--timeToIdleSeconds设置某个元素消亡前的停顿时间。 也就是在一个元素消亡之前,两次访问时间的最大时间间隔值。这只能在元素不是永久驻留时有效(译注:如果对象永恒不灭,则设置该属性也无用)。如果该值是 0就意味着元素可以停顿无穷长的时间。 -->
<!-- timeToLiveSeconds为元素设置消亡前的生存时间。也就是一个元素从构建到消亡的最大时间间隔值。 这只能在元素不是永久驻留时有效。-->
<!-- diskPersistent是否disk store在虚拟机启动时持久化。默认为false-->
<!--diskExpiryThreadIntervalSeconds运行disk终结线程的时间,默认为120秒-->
<!--MemoryStore支持三种策略:LRU、LFU、FIFO。
1.LRU:最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清除缓存。
2.LFU:最少被使用,缓存的元素有一个hit属性,hit值最小的将会被清除缓存。
3.FIFO:先进先出-->
<diskStorepath="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="500"
timeToLiveSeconds="1000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"/>
<cachename="userCache" maxElementsInMemory="50000"
maxElementsOnDisk="2000" eternal="false"overflowToDisk="true"
diskSpoolBufferSizeMB="20" timeToIdleSeconds="300"timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LFU" />
</ehcache>
四、测试类
1、EhCacheProvider.java
public class EhCacheProvider {
privatestatic final Log logger =LogFactory.getLog(EhCacheProvider.class);
privatestatic ClassPathXmlApplicationContext ctxt;
static{
ctxt = newClassPathXmlApplicationC