Spring整合ehcache

20150505171917
20150505171928

ehcache参数说明

name:cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)。如果在CacheManager中直接加入了一个其他名字的cache,系统会把defaultCache的设置给它clone一份。
maxElementsInMemory:cache 中最多可以存放的元素的数量。如果放入cache中的元素超过这个数值,有两种情况:1、若overflowToDisk的属性值为true,会将cache中多出的元素放入磁盘文件中。2、若overflowToDisk的属性值为false,会根据memoryStoreEvictionPolicy的策略替换cache中原有的元素。
eternal :意思是是否永驻内存。如果值是true,cache中的元素将一直保存在内存中,不会因为时间超时而丢失,所以在这个值为true的时候,timeToIdleSeconds和timeToLiveSeconds两个属性的值就不起作用了。

timeToIdleSeconds:就是访问这个cache中元素的最大间隔时间。如果超过这个时间没有访问这个cache中的某个元素,那么这个元素将被从cache中清除。
timeToLiveSeconds:这是cache中元素的生存时间。意思是从cache中的某个元素从创建到消亡的时间,从创建开始计时,当超过这个时间,这个元素将被从cache中清除。
overflowToDisk:溢出是否写入磁盘。系统会根据标签 中path的值查找对应的属性值,如果系统的java.io.tmpdir的值是 D:/temp,写入磁盘的文件就会放在这个文件夹下。文件的名称是cache的名称,后缀名的data。如:CACHE_FUNC.data。这个属性在解释maxElementsInMemory的时候也已经说过了。
diskExpiryThreadIntervalSeconds:磁盘缓存的清理线程运行间隔。
memoryStoreEvictionPolicy:内存存储与释放策略。有三个值:
LRU -least recently used (最近最少使用的算法)
LFU -least frequently used (最近最不常用页面置换算法)
FIFO-first in first out, the oldest element by creation time (先进先出)
diskPersistent:是否持久化磁盘缓存。当这个属性的值为true时,系统在初始化的时候会在磁盘中查找文件名为cache名称,后缀名为index的的文件,如CACHE_FUNC.index 。这个文件中存放了已经持久化在磁盘中的cache的index,找到后把cache加载到内存。要想把cache真正持久化到磁盘,写程序时必须注意,在是用net.sf.ehcache.Cache的void put (Element element)方法后要使用void flush()方法。
diskSpoolBufferSizeMB:是为后台打印缓冲分配在DiskStore的大小。在这一区域进行写入,并同步写入磁盘。默认值是30M。每个后台缓冲区仅由他的缓存使用,如出现OutOfMemory错误,考虑降低该值。为了提高DiskStore性能,考虑增加它。跟踪级别的DiskStore工作 将显示是否推迟出现。
clearOnFlush:当flush()在缓存中被调用时,MemoryStore是否被清除。默认是true,即MemoryStore被清除。
以上时间值都是以秒作为单位的。

ehcache基本用法

CacheManager cacheManager = CacheManager.create();
// 或者
cacheManager = CacheManager.getInstance();
// 或者
cacheManager = CacheManager.create("/config/ehcache.xml");
// 或者
cacheManager = CacheManager.create("http://localhost:8080/test/ehcache.xml");
cacheManager = CacheManager.newInstance("/config/ehcache.xml");
// .......
// 获取ehcache配置文件中的一个cache
Cache sample = cacheManager.getCache("sample");
// 获取页面缓存
BlockingCache cache = new BlockingCache(cacheManager.getEhcache("SimplePageCachingFilter"));
// 添加数据到缓存中
Element element = new Element("key", "val");
sample.put(element);
// 获取缓存中的对象,注意添加到cache中对象要序列化 实现Serializable接口
Element result = sample.get("key");
// 删除缓存
sample.remove("key");
sample.removeAll();
// 获取缓存管理器中的缓存配置名称
for (String cacheName : cacheManager.getCacheNames()) {
    System.out.println(cacheName);
}
// 获取所有的缓存对象
for (Object key : cache.getKeys()) {
    System.out.println(key);
}
// 得到缓存中的对象数
cache.getSize();
// 得到缓存对象占用内存的大小
cache.getMemoryStoreSize();
// 得到缓存读取的命中次数
cache.getStatistics().getCacheHits();
// 得到缓存读取的错失次数
cache.getStatistics().getCacheMisses();

示例下载:DEMO

参考资料:
spring cache注解:http://hanqunfeng.iteye.com/blog/1158824
ehcache 整合Spring:http://www.cnblogs.com/hoojo/archive/2012/07/12/2587556.html


已发布

分类

来自

标签:

评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注