一、准备工作
需要依赖 jar 包:
1.ehcache核心包
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
</dependency>
2.spring 扩展包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
二、编程开发
1.ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="TestCache">
<diskStore path="java.io.tmpdir/ehcache/threeBro" />
<!-- DefaultCache setting. -->
<defaultCache maxEntriesLocalHeap="10000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="7200"
overflowToDisk="true" maxEntriesLocalDisk="100000" />
<!-- Special objects setting. -->
<!-- 配置自定义缓存
maxElementsInMemory:缓存中允许创建的最大对象数
eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。
timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前,
两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,
如果该值是 0 就意味着元素可以停顿无穷长的时间。
timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,
这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。
overflowToDisk:内存不足时,是否启用磁盘缓存。
memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。-->
<cache name="defaultThreeBroCache" maxElementsInMemory="100000" eternal="false" timeToIdleSeconds="21600"
timeToLiveSeconds="43200" overflowToDisk="false" memoryStoreEvictionPolicy = "LFU" />
</ehcache>
2.EhCacheTool.javapackage com.saber.domain;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class EhCacheTool {
@Autowired
@Qualifier("simpleCache")
public Ehcache ehcache;
public void put(Object key, Object value) {
Element element = new Element(key, value);
ehcache.put(element);
}
public Object get(Object key) {
Element element = ehcache.get(key);
if(element == null) {
return null;
}
return element.getObjectValue();
}
public boolean remove(Object key) {
Element element = ehcache.get(key);
if(element == null) {
return true;
}
return ehcache.remove(key);
}
}
3.applicationContext.xml
<!--缓存配置-->
<bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache/ehcache.xml"/>
</bean>
<!-- 配置一个简单的缓存工厂bean对象 -->
<bean id="simpleCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager" ref="cacheManagerFactory" />
<!-- 使用缓存 关联ehcache.xml中的缓存配置 -->
<property name="cacheName" value="defaultTestCache" />
</bean>
三、测试
略