ehcache架构.png
<ehcache>
<!--<diskStore path="java.io.tmpdir"/> -->
<diskStore path="data/ehcache" />
<defaultCache maxElementsInMemory="10000" eternal="false"
overflowToDisk="true" timeToIdleSeconds="120" timeToLiveSeconds="120"
diskPersistent="false" diskExpiryThreadIntervalSeconds="120" />
<cache name="tagCache" maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="300" timeToLiveSeconds="1800" overflowToDisk="true"
diskPersistent="false" />
</ehcache>
配置的一些参数含义如下:
maxElementsInMemory:设置缓存中允许存放的最大条目数量 eternal:缓存内容是否永久存储在内存;该值设置为true时,timeToIdleSeconds和timeToLiveSeconds两个属性的值就不起作用了。 overflowToDisk:如果内存中的数据超过maxElementsInMemory,是否使用磁盘存储。 timeToLiveSeconds:缓存自创建日期起至失效时的间隔时间; timeToIdleSeconds:缓存创建以后,最后一次访问缓存的日期至失效之时的时间间隔; 如果仅有timeToLiveSeconds那么自创建时间开始 间隔x后缓存失效; 如果没有timeToLiveSeconds那么自最后一次访问缓存 间隔y后 缓存失效; 如果既有timeToLiveSeconds也有timeToIdleSeconds那么取最小数算作间隔时间;min(x,y); diskPersistent:磁盘存储的条目是否永久保存 diskExpiryThreadIntervalSeconds:磁盘清理线程的运行时间间隔 注意:时间都是以秒为单位 配置完ehcache.xml之后,就可以写一个EHCacheUtil类了:
/**
* 对EHCache进行了简单的封装
* 建议在频繁使用且重负载的函数实现中使用缓存
* Ehcache会将每个缓存配置的文件路径下创建一个cache_name.data文件,如果使用的磁盘持久化技术,还会生成一个cache name.index文件。
* @author kouyy
*/
public class EHCacheUtil {
static CacheManager manager=null;
static String configfile="ehcache.xml";
//EHCache初始化
static{
try {
manager = CacheManager.create(EHCacheUtil.class.getClassLoader().getResourceAsStream(configfile));
} catch (CacheException e) {
e.printStackTrace();
}
}
/**
* 将数据存入Cache
* @param cachename Cache名称
* @param key 类似redis的Key
* @param value 类似redis的value,value可以是任何对象、数据类型,比如person,map,list等
*/
public static void put(String cachename,Serializable key,Serializable value){
manager.getCache(cachename).put(new Element(key, value));
}
/**
* 获取缓存cachename中key对应的value
* @param cachename
* @param key
* @return
*/
public static Serializable get(String cachename,Serializable key){
try {
Element e=manager.getCache(cachename).get(key);
if(e==null){
return null;
}
return e.getValue();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (CacheException e) {
e.printStackTrace();
}
return null;
}
/**
* 清除缓存名称为cachename的缓存
* @param cachename
*/
public static void clearCache(String cachename){
try {
manager.getCache(cachename).removeAll();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
/**
* 移除缓存cachename中key对应的value
* @param cachename
* @param key
*/
public static void remove(String cachename,Serializable key){
manager.getCache(cachename).remove(key);
}
}
实际操作很像redis,都是对key-value的操作,只是ehcache在每次操作的时候需要指明缓存的名称,仅此而已。 在同类的Java缓存框架中,Ehcache配置相对简单,也比较容易上手,最大的优势是它支持分布式缓存。