Ehcache由Hibernate发展而来,具备快速、低消耗、内存缓存、磁盘缓存等优势。java
ehcache-2.10.4-distribution.tar.gz和ehcache-web-2.0.4-distribution.gzweb
ehcache的ehcache-2.10.4.jar包中含有ehcache-failsafe.xml这是ehcache的默认配置文件,当使用CacheManager.create()默认构造CacheManager时,引用的就是ehcache-failsafe.xml中的cache;缓存
ehcache-failsafe.xml内容以下:spa
<defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </defaultCache>
其中maxElementsInMemory为内存中最大缓存数;eternal为Element是否永久化,一旦设置为true,则timeout将不起做用;timeToIdleSecondes为Element失效前容许的闲置时间,当设置为0时,标识无限长;timeToLiveSecondes为Element失效前容许的存活时间,0表示无限长;maxElementsOnDisk表示磁盘存储Element的最大数量;diskExpiryThreadIntervalSeconds为磁盘失效线程运行时间间隔;memoryStoreEvictionPolicy表示到达maxElementsInMemory上限时,Ehcache会根据指定策略去清理内存;策略方式有三种:LRU(默认清除内容策略),最近最少使用策略;FIFO,先进先出;LFU较少使用;线程
1)使用默认配置文件建立code
CacheManager manager = CacheManager.create();
2)使用指定文件建立xml
CacheManager manager2 = CacheManager.create("src/ehcache.xml");
3)从classpath中获取配置文件建立ip
CacheManager manager3 = CacheManager.create(getClass().getResource("encache.xml"));
4)以流的形式读取配置文件建立内存
InputStream fis = new FileInputStream(new File("D://MyEclipseWS/DJSQWorkSpace/MyDJSQ/config/encache.xml")); CacheManager manager4 = CacheManager.create(fis);
1)经过cacheName获取element
String[] cacheNames = manager2.getCacheNames(); Cache cache1 = manager2.getCache(cacheNames[0]);
2)自定义cache
Cache cache = new Cache("myCache", 1, true, false, 3, 2);
1)存入缓存
String s[]={"aa","bb","cc"}; List<String> asList = Arrays.asList(s); cache1.put(new Element("key1",asList));
2)获取缓存值
Element element = cache1.get("key1"); List<String> value1 = (List<String>) element.getObjectValue();
3)删除cache缓存中的值
cache1.remove("key");
4)清除cacheManager,关闭cache
cacheManger.shutdown();