Ehcache是一个很强大的轻量级框架,不依赖除了slf4j以外的任何包,这篇文章主要是了解一下ehcache的简单使用,对Ehcache做一个简单了解
首先要了解缓存清除策略,官方文档给出的有
- LRU - least recently used(最近最少使用)
- LFU - least frequently used(最不经常使用)
- FIFO - first in first out, the oldest element by creation time(清除最早缓存的数据,不关心是否经常使用)
使用配置文件的方式:
ehcache-test.xml
- <?xmlversion="1.0"encoding="UTF-8"?>
- <ehcachexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
- <diskStorepath="G:/development/workspace/test/WebContent/cache/temporary"/><!--达到内存上限后缓存文件保存位置-->
- <defaultCache
- maxElementsInMemory="10000"<!--最大内存占用,超出后缓存保存至文件-->
- memoryStoreEvictionPolicy="LRU"<!--缓存废弃策略,LRU表示最少使用的优先清除,此值对应之前3种策略-->
- eternal="false"
- timeToIdleSeconds="1"<!--空闲时间,超出此时间未使用缓存自动清除-->
- timeToLiveSeconds="5"<!--清除时间,缓存保留的最长时间-->
- overflowToDisk="false"<!--是否往硬盘写缓存数据-->
- diskPersistent="false"/>
- <!--测试-->
- <cache
- name="cache_test"<!--缓存名称-->
- memoryStoreEvictionPolicy="LRU"
- maxElementsInMemory="1"
- eternal="false"
- timeToIdleSeconds="7200"
- timeToLiveSeconds="7200"
- overflowToDisk="true"/>
- </ehcache>
使用缓存首先要创建CacheManager,穿件方法有多种,此处使用create(URL)方法
- CacheManagercacheManager=CacheManager.create(URL);//URL是指配置文件所在路径的URL,通常使用getClass().getResource("/config/ehcache/ehcache-test.xml")获取
创建完成后就可以使用了,添加缓存
- //key:根据此值获取缓存的value,不可重复,value值需要缓存的数据
- Elementelement=newElement(key,value);
- //cacheName:指ehcache-test.xml配置文件中的缓存名称name="xxx"中的值
- Cachecache=cacheManager.getCache(cacheName);
- cache.put(element);
获取缓存