Spring整合Ehcache
一、整合Ehcache
1、需要echache的jar包可以直接去maven仓库下载
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.8.2</version>
</dependency>
2、需要配置文件ehcache.xml进行配置
3、修改配置文件ehcache.xml ,例如添加配置如下:
<?xml version="1.0" encoding="UTF-8" ?>
<ehcache>
<diskStore />
<!-- 默认缓存 -->
<defaultCache
maxEntriesLocalHeap="1000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="3600"
overflowToDisk="false">
</defaultCache>
<cache name="reportCache"
maxElementsInMemory="500" <!-- 最大缓存数量 -->
eternal="false" <!-- true:在内存中永久存在,false:不在内存中永久存在 -->
timeToIdleSeconds="3600" <!-- 一个小时之内不再用到这个缓存就清理 -->
timeToLiveSeconds="7200" <!-- 两个小时以后不管是否用到这个缓存都会被清理 -->
overflowToDisk="false"/> <!-- 当超过500是不会写入磁盘 -->
<cache name="diskCache" <!-- 以上两种都是内存缓存,这里配置的是磁盘缓存 -->
maxElementsInMemory="10000"
overflowToDisk="true" <!-- 当内存中超过10000, 就写入磁盘 -->
eternal="false"
memoryStoreEvictionPolicy="LRU" <!-- 这里配置的是清除缓存时的策略 -->
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="600"
timeToIdleSeconds="3600"
timeToLiveSeconds="100000"
diskPersistent="false" /> <!-- 不是磁盘永存 -->
</ehcache>
这里就建立了三种缓存形式
4、可以建立一个或者多个独立的类,用于对应配置文件中的配置,例如:
package com.cetc32.cache;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
public class ReportCache {
private static ReportCache reportCache = null;
private static Cache cache = null;
//实现单例模式
public static ReportCache getInstance() {
if(reportCache == null) {
reportCache = new ReportCache();
}
return reportCache;
}
//private Cache cache;
public ReportCache() {
String path = this.getClass().getResource("/config/ehcache.xml").getFile();
CacheManager manager = CacheManager.create(path);
cache = manager.getCache("reportCache");
}
/**
* 设置缓存
* @param key
* @param o
*/
public void setReportCache(String key, Object o) {
Element element = new Element(key, o);
cache.put(element);
}
/**
* 从缓存中获得结果
* @param key
* @return
*/
public Object getReportCache(String key) {
Element aa = cache.get(key);
Object r = null;
if (aa != null) {
r = aa.getObjectValue();
}
return r;
}
/**
* 清除某个缓存
* @param key
*/
public boolean removeReportCache(String key) {
return cache.remove(key);
}
/**
* 清空全部缓存
*/
public void removeAllReportCache() {
cache.removeAll();
}
/**
* @return the cache
*/
public Cache getCache() {
return cache;
}
}
这里采用的是单例模式,应用中一个实例即可
6、在程序中使用 ReportCache reportCache = ReportCache.getInstance(); 获取实例就可以进行缓存操作了。