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
- <?xml version="1.0" encoding="UTF-8"?>
- <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
-
- <diskStore path="G:/development/workspace/test/WebContent/cache/temporary"/>
-
- <defaultCache
- maxElementsInMemory="10000"
- memoryStoreEvictionPolicy="LRU"
- 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)方法
- CacheManager cacheManager = CacheManager.create(URL);
创建完成后就可以使用了,添加缓存
-
- Element element = new Element(key, value);
-
- Cache cache = cacheManager.getCache(cacheName);
- cache.put(element);
获取缓存
- Cache cache = cacheManager.getCache(cacheName);
- Element element = cache.get(key);
- Object data = element.getObjectValue();