Ehcache是用于配置管理缓存的一个缓存框架,我们从它的ehcache.xml文件中分析,它是如何将数据插入内存和硬盘中。
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <diskStore path="java.io.tmpdir" /> <defaultCache maxElementsInMemory="500" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="1200" overflowToDisk="true" /> <cache name="testcache" maxElementsInMemory="150" eternal="false" timeToLiveSeconds="36000" timeToIdleSeconds="3600" overflowToDisk="true"/> </ehcache>
<diskStore path="java.io.tmpdir" />就是配置缓存存入硬盘的路径,它指向操作系统的一个临时文件存放路径,可以通过System.getProperty("java.io.tmpdir")获取路径信息。
maxElementsInMemory=500这个是配置内存最大对象数的
overflowToDisk="true"当超过500时它就会存入硬盘中配置好的路径下面。
可以写段代码改变循环次数:100,400,2000测试,观察目录下面是否有文件生成:
package com.xxinfo.ylzcache;
import org.apache.log4j.Logger;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
public class EhcacheTest {
private static final Logger logger = Logger.getLogger(EhcacheTest.class);
private static Cache sampleCache = null;
public static void main(String[] args) {
init();
test();
}
private static void test() {
logger.info(sampleCache.getMemoryStoreEvictionPolicy());
for(int i=0; i<2000; i++){
//写入缓存
sampleCache.put(new Element(i, "v" + i));
//打印当前缓存的所有值
logger.info(sampleCache.getKeys());
//读取缓存
Element e = sampleCache.get(i);
logger.info(e.getValue());
}
//打印命中统计
logger.info(sampleCache.getStatistics());
CacheManager.getInstance().shutdown() ;
}
private static void init() {
CacheManager manager = CacheManager.create();
sampleCache = manager.getCache("testcache");
}
}
EHcache缓存写入内存和硬盘机制,布布扣,bubuko.com
原文地址:http://blog.csdn.net/asartear/article/details/38467375