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();