ehcache常用API整理

博客分類: java

鑑於csdn的blog的不穩定, 及混亂的編輯器, 和無上傳功能, 遂決定徹底投誠javaeye的blog.

數月前整理的一個東西, 作爲cache的掃盲文檔.參考了它的官方文檔.

對ehcache感興趣的兄臺可以參考.

附件爲eclipse項目, 直接導入, 運行test目錄下的junit testcase, 可一目瞭然.
一 ehcache API:

1: Using the CacheManager

1.1所有ehcache的使用, 都是從 CacheManager. 開始的.
有多種方法創建CacheManager實例:

Java代碼 複製代碼 收藏代碼
  1. //Create a singleton CacheManager using defaults, then list caches.  
  2. CacheManager.getInstance()  
  1. //Create a singleton CacheManager using defaults, then list caches.  
  2. CacheManager.getInstance()  
 


或者:

Java代碼 複製代碼 收藏代碼
  1. //Create a CacheManager instance using defaults, then list caches.  
  2. CacheManager manager = new CacheManager();  
  3. String[] cacheNames = manager.getCacheNames();  
  1. //Create a CacheManager instance using defaults, then list caches.  
  2. CacheManager manager = new CacheManager();  
  3. String[] cacheNames = manager.getCacheNames();  
 



如果需要從指定配置文件創建 CacheManager:

Java代碼 複製代碼 收藏代碼
  1. Create two CacheManagers, each with a different configuration, and list the caches in each.  
  2. CacheManager manager1 = new CacheManager("src/config/ehcache1.xml");  
  3. CacheManager manager2 = new CacheManager("src/config/ehcache2.xml");  
  4. String[] cacheNamesForManager1 = manager1.getCacheNames();  
  5. String[] cacheNamesForManager2 = manager2.getCacheNames();  
  1. Create two CacheManagers, each with a different configuration, and list the caches in each.  
  2. CacheManager manager1 = new CacheManager("src/config/ehcache1.xml");  
  3. CacheManager manager2 = new CacheManager("src/config/ehcache2.xml");  
  4. String[] cacheNamesForManager1 = manager1.getCacheNames();  
  5. String[] cacheNamesForManager2 = manager2.getCacheNames();  
 



1.2 Adding and Removing Caches Programmatically
手動創建一個cache, 而不是通過配置文件:

Java代碼 複製代碼 收藏代碼
  1. //creates a cache called testCache, which  
  2. //will be configured using defaultCache from the configuration  
  3. CacheManager singletonManager = CacheManager.create();  
  4. singletonManager.addCache("testCache");  
  5. Cache test = singletonManager.getCache("testCache");  
  1. //creates a cache called testCache, which  
  2. //will be configured using defaultCache from the configuration  
  3. CacheManager singletonManager = CacheManager.create();  
  4. singletonManager.addCache("testCache");  
  5. Cache test = singletonManager.getCache("testCache");  
 

或者:

Java代碼 複製代碼 收藏代碼
  1. //Create a Cache and add it to the CacheManager, then use it. Note that Caches are not usable until they have  
  2. //been added to a CacheManager.  
  3.     public void testCreatCacheByProgram()  
  4.     {  
  5.         CacheManager singletonManager = CacheManager.create();  
  6.         Cache memoryOnlyCache = new Cache("testCache"5000falsefalse52);  
  7.         singletonManager.addCache(memoryOnlyCache);  
  8.         Cache testCache = singletonManager.getCache("testCache");  
  9.         assertNotNull(testCache);         
  10.     }  
  1. //Create a Cache and add it to the CacheManager, then use it. Note that Caches are not usable until they have  
  2. //been added to a CacheManager.  
  3.     public void testCreatCacheByProgram()  
  4.     {  
  5.         CacheManager singletonManager = CacheManager.create();  
  6.         Cache memoryOnlyCache = new Cache("testCache"5000falsefalse52);  
  7.         singletonManager.addCache(memoryOnlyCache);  
  8.         Cache testCache = singletonManager.getCache("testCache");  
  9.         assertNotNull(testCache);         
  10.     }  
 

   
手動移除一個cache:

Java代碼 複製代碼 收藏代碼
  1. //Remove cache called sampleCache1  
  2. CacheManager singletonManager = CacheManager.create();  
  3. singletonManager.removeCache("sampleCache1");  
  1. //Remove cache called sampleCache1  
  2. CacheManager singletonManager = CacheManager.create();  
  3. singletonManager.removeCache("sampleCache1");  
 


1.3 Shutdown the CacheManager
ehcache應該在使用後關閉, 最佳實踐是在code中顯式調用:

Java代碼 複製代碼 收藏代碼
  1. //Shutdown the singleton CacheManager  
  2. CacheManager.getInstance().shutdown();  
  1. //Shutdown the singleton CacheManager  
  2. CacheManager.getInstance().shutdown();  

 2 Using Caches
比如我有這樣一個cache:

Xml代碼 複製代碼 收藏代碼
  1. <cache name="sampleCache1" maxElementsInMemory="10000"  
  2.     maxElementsOnDisk="1000" eternal="false" overflowToDisk="true"  
  3.     diskSpoolBufferSizeMB="20" timeToIdleSeconds="300"  
  4.     timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" />  
  1. <cache name="sampleCache1" maxElementsInMemory="10000"  
  2.     maxElementsOnDisk="1000" eternal="false" overflowToDisk="true"  
  3.     diskSpoolBufferSizeMB="20" timeToIdleSeconds="300"  
  4.     timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" />  
 


       
2.1 Obtaining a reference to a Cache
獲得該cache的引用:

Java代碼 複製代碼 收藏代碼
  1. String cacheName = "sampleCache1";  
  2. CacheManager manager = new CacheManager("src/ehcache1.xml");  
  3. Cache cache = manager.getCache(cacheName);  
  1. String cacheName = "sampleCache1";  
  2. CacheManager manager = new CacheManager("src/ehcache1.xml");  
  3. Cache cache = manager.getCache(cacheName);  

 
2.2 Performing CRUD operations
下面的代碼演示了ehcache的增刪改查:

Java代碼 複製代碼 收藏代碼
  1. public void testCRUD()  
  2. {  
  3.     String cacheName = "sampleCache1";  
  4.     CacheManager manager = new CacheManager("src/ehcache1.xml");  
  5.     Cache cache = manager.getCache(cacheName);  
  6.     //Put an element into a cache  
  7.     Element element = new Element("key1""value1");  
  8.     cache.put(element);  
  9.     //This updates the entry for "key1"  
  10.     cache.put(new Element("key1""value2"));  
  11.     //Get a Serializable value from an element in a cache with a key of "key1".  
  12.     element = cache.get("key1");  
  13.     Serializable value = element.getValue();  
  14.     //Get a NonSerializable value from an element in a cache with a key of "key1".  
  15.     element = cache.get("key1");  
  16.     assertNotNull(element);  
  17.     Object valueObj = element.getObjectValue();  
  18.     assertNotNull(valueObj);  
  19.     //Remove an element from a cache with a key of "key1".  
  20.     assertNotNull(cache.get("key1"));  
  21.     cache.remove("key1");  
  22.     assertNull(cache.get("key1"));  
  23.      
  24. }  
  1. public void testCRUD()  
  2. {  
  3.     String cacheName = "sampleCache1";  
  4.     CacheManager manager = new CacheManager("src/ehcache1.xml");  
  5.     Cache cache = manager.getCache(cacheName);  
  6.     //Put an element into a cache  
  7.     Element element = new Element("key1""value1");  
  8.     cache.put(element);  
  9.     //This updates the entry for "key1"  
  10.     cache.put(new Element("key1""value2"));  
  11.     //Get a Serializable value from an element in a cache with a key of "key1".  
  12.     element = cache.get("key1");  
  13.     Serializable value = element.getValue();  
  14.     //Get a NonSerializable value from an element in a cache with a key of "key1".  
  15.     element = cache.get("key1");  
  16.     assertNotNull(element);  
  17.     Object valueObj = element.getObjectValue();  
  18.     assertNotNull(valueObj);  
  19.     //Remove an element from a cache with a key of "key1".  
  20.     assertNotNull(cache.get("key1"));  
  21.     cache.remove("key1");  
  22.     assertNull(cache.get("key1"));  
  23.      
  24. }  

    
2.3    Disk Persistence on demand

Java代碼 複製代碼 收藏代碼
  1. //sampleCache1 has a persistent diskStore. We wish to ensure that the data //and index are written immediately.  
  2.         public void testDiskPersistence()  
  3.     {  
  4.         String cacheName = "sampleCache1";  
  5.         CacheManager manager = new CacheManager("src/ehcache1.xml");  
  6.         Cache cache = manager.getCache(cacheName);  
  7.         for (int i = 0; i < 50000; i++)  
  8.         {  
  9.             Element element = new Element("key" + i, "myvalue" + i);  
  10.             cache.put(element);  
  11.         }  
  12.         cache.flush();  
  13.         Log.debug("java.io.tmpdir = " + System.getProperty("java.io.tmpdir"));  
  14.     }  
  1. //sampleCache1 has a persistent diskStore. We wish to ensure that the data //and index are written immediately.  
  2.         public void testDiskPersistence()  
  3.     {  
  4.         String cacheName = "sampleCache1";  
  5.         CacheManager manager = new CacheManager("src/ehcache1.xml");  
  6.         Cache cache = manager.getCache(cacheName);  
  7.         for (int i = 0; i < 50000; i++)  
  8.         {  
  9.             Element element = new Element("key" + i, "myvalue" + i);  
  10.             cache.put(element);  
  11.         }  
  12.         cache.flush();  
  13.         Log.debug("java.io.tmpdir = " + System.getProperty("java.io.tmpdir"));  
  14.     }  
 


備註: 持久化到硬盤的路徑由虛擬機參數"Java.io.tmpdir"決定.
例如, 在windows中, 會在此路徑下
C:\Documents and Settings\li\Local Settings\Temp
在linux中, 通常會在: /tmp 下

2.4  Obtaining Cache Sizes
以下代碼演示如何獲得cache個數:

Java代碼 複製代碼 收藏代碼
  1. public void testCachesizes()  
  2. {  
  3.     long count = 5;  
  4.     String cacheName = "sampleCache1";  
  5.     CacheManager manager = new CacheManager("src/ehcache1.xml");  
  6.     Cache cache = manager.getCache(cacheName);  
  7.     for (int i = 0; i < count; i++)  
  8.     {  
  9.         Element element = new Element("key" + i, "myvalue" + i);  
  10.         cache.put(element);  
  11.     }  
  12.     //Get the number of elements currently in the Cache.  
  13.     int elementsInCache = cache.getSize();  
  14.     assertTrue(elementsInCache == 5);  
  15.     //Cache cache = manager.getCache("sampleCache1");  
  16.     long elementsInMemory = cache.getMemoryStoreSize();  
  17.     //Get the number of elements currently in the DiskStore.  
  18.     long elementsInDiskStore = cache.getDiskStoreSize();  
  19.     assertTrue(elementsInMemory + elementsInDiskStore == count);     
  20. }  
  1. public void testCachesizes()  
  2. {  
  3.     long count = 5;  
  4.     String cacheName = "sampleCache1";  
  5.     CacheManager manager = new CacheManager("src/ehcache1.xml");  
  6.     Cache cache = manager.getCache(cacheName);  
  7.     for (int i = 0; i < count; i++)  
  8.     {  
  9.         Element element = new Element("key" + i, "myvalue" + i);  
  10.         cache.put(element);  
  11.     }  
  12.     //Get the number of elements currently in the Cache.  
  13.     int elementsInCache = cache.getSize();  
  14.     assertTrue(elementsInCache == 5);  
  15.     //Cache cache = manager.getCache("sampleCache1");  
  16.     long elementsInMemory = cache.getMemoryStoreSize();  
  17.     //Get the number of elements currently in the DiskStore.  
  18.     long elementsInDiskStore = cache.getDiskStoreSize();  
  19.     assertTrue(elementsInMemory + elementsInDiskStore == count);     
  20. }  
 


3: Registering CacheStatistics in an MBeanServer
ehCache 提供jmx支持:

Java代碼 複製代碼 收藏代碼
  1. CacheManager manager = new CacheManager();  
  2. MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();  
  3. ManagementService.registerMBeans(manager, mBeanServer, falsefalsefalsetrue);  
  1. CacheManager manager = new CacheManager();  
  2. MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();  
  3. ManagementService.registerMBeans(manager, mBeanServer, falsefalsefalsetrue);  
 


把該程序打包, 然後:

Java代碼 複製代碼 收藏代碼
  1. java -Dcom.sun.management.jmxremote -jar 程序名.jar  
  1. java -Dcom.sun.management.jmxremote -jar 程序名.jar  

 
再到javahome/bin中運行jconsole.exe, 便可監控cache.

4. 用戶可以自定義處理cacheEventHandler, 處理諸如元素放入cache的各種事件(放入,移除,過期等事件)
只需三步:
4.1 在cache配置中, 增加cacheEventListenerFactory節點.

Java代碼 複製代碼 收藏代碼
  1. <cache name="Test" maxElementsInMemory="1" eternal="false"  
  2.     overflowToDisk="true" timeToIdleSeconds="1" timeToLiveSeconds="2"  
  3.     diskPersistent="false" diskExpiryThreadIntervalSeconds="1"  
  4.     memoryStoreEvictionPolicy="LFU">  
  5.     <cacheEventListenerFactory class="co.ehcache.EventFactory" />  
  6. </cache>  
  1. <cache name="Test" maxElementsInMemory="1" eternal="false"  
  2.     overflowToDisk="true" timeToIdleSeconds="1" timeToLiveSeconds="2"  
  3.     diskPersistent="false" diskExpiryThreadIntervalSeconds="1"  
  4.     memoryStoreEvictionPolicy="LFU">  
  5.     <cacheEventListenerFactory class="co.ehcache.EventFactory" />  
  6. </cache>  

 

4.2: 編寫EventFactory, 繼承CacheEventListenerFactory:

Java代碼 複製代碼 收藏代碼
  1. public class EventFactory extends CacheEventListenerFactory   
  2. {  
  3.     @Override  
  4.     public CacheEventListener createCacheEventListener(Properties properties)  
  5.     {  
  6.         // TODO Auto-generated method stub  
  7.         return new CacheEvent();  
  8.     }  
  9.   
  10. }  
  1. public class EventFactory extends CacheEventListenerFactory   
  2. {  
  3.     @Override  
  4.     public CacheEventListener createCacheEventListener(Properties properties)  
  5.     {  
  6.         // TODO Auto-generated method stub  
  7.         return new CacheEvent();  
  8.     }  
  9.   
  10. }  

 


4.3  編寫 class: CacheEvent, 實現 CacheEventListener 接口:

Java代碼 複製代碼 收藏代碼
  1. public class CacheEvent implements CacheEventListener   
  2. {  
  3.   
  4.     public void dispose()  
  5.     {  
  6.         log("in dispose");  
  7.     }  
  8.   
  9.     public void notifyElementEvicted(Ehcache cache, Element element)  
  10.     {  
  11.         // TODO Auto-generated method stub  
  12.         log("in notifyElementEvicted" + element);  
  13.     }  
  14.   
  15.     public void notifyElementExpired(Ehcache cache, Element element)  
  16.     {  
  17.         // TODO Auto-generated method stub  
  18.         log("in notifyElementExpired" + element);  
  19.     }  
  20.   
  21.     public void notifyElementPut(Ehcache cache, Element element) throws CacheException  
  22.     {  
  23.         // TODO Auto-generated method stub  
  24.         log("in notifyElementPut" + element);  
  25.     }  
  26.   
  27.     public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException  
  28.     {  
  29.         // TODO Auto-generated method stub  
  30.         log("in notifyElementRemoved" + element);  
  31.     }  
  32.   
  33.     public void notifyElementUpdated(Ehcache cache, Element element) throws CacheException  
  34.     {  
  35.         // TODO Auto-generated method stub  
  36.         log("in notifyElementUpdated" + element);  
  37.     }  
  38.   
  39.     public void notifyRemoveAll(Ehcache cache)  
  40.     {  
  41.         // TODO Auto-generated method stub  
  42.         log("in notifyRemoveAll");  
  43.     }  
  44.      
  45.     public Object clone() throws CloneNotSupportedException  
  46.     {  
  47.         return super.clone();  
  48.     }     
  49.      
  50.     private void log(String s)  
  51.     {  
  52.         Log.debug(s);  
  53.     }  
  54. }  
  1. public class CacheEvent implements CacheEventListener   
  2. {  
  3.   
  4.     public void dispose()  
  5.     {  
  6.         log("in dispose");  
  7.     }  
  8.   
  9.     public void notifyElementEvicted(Ehcache cache, Element element)  
  10.     {  
  11.         // TODO Auto-generated method stub  
  12.         log("in notifyElementEvicted" + element);  
  13.     }  
  14.   
  15.     public void notifyElementExpired(Ehcache cache, Element element)  
  16.     {  
  17.         // TODO Auto-generated method stub  
  18.         log("in notifyElementExpired" + element);  
  19.     }  
  20.   
  21.     public void notifyElementPut(Ehcache cache, Element element) throws CacheException  
  22.     {  
  23.         // TODO Auto-generated method stub  
  24.         log("in notifyElementPut" + element);  
  25.     }  
  26.   
  27.     public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException  
  28.     {  
  29.         // TODO Auto-generated method stub  
  30.         log("in notifyElementRemoved" + element);  
  31.     }  
  32.   
  33.     public void notifyElementUpdated(Ehcache cache, Element element) throws CacheException  
  34.     {  
  35.         // TODO Auto-generated method stub  
  36.         log("in notifyElementUpdated" + element);  
  37.     }  
  38.   
  39.     public void notifyRemoveAll(Ehcache cache)  
  40.     {  
  41.         // TODO Auto-generated method stub  
  42.         log("in notifyRemoveAll");  
  43.     }  
  44.      
  45.     public Object clone() throws CloneNotSupportedException  
  46.     {  
  47.         return super.clone();  
  48.     }     
  49.      
  50.     private void log(String s)  
  51.     {  
  52.         Log.debug(s);  
  53.     }  
  54. }  
 

現在可以編寫測試代碼:

Java代碼 複製代碼 收藏代碼
  1. public void testEventListener()  
  2. {  
  3.     String key = "person";  
  4.     Person person = new Person("lcl"100);  
  5.     MyCacheManager.getInstance().put("Test", key, person);  
  6.     Person p = (Person) MyCacheManager.getInstance().get("Test", key);  
  7.   
  8.     try  
  9.     {  
  10.         Thread.sleep(10000);  
  11.     }  
  12.     catch (InterruptedException e)  
  13.     {  
  14.         // TODO Auto-generated catch block  
  15.         e.printStackTrace();  
  16.     }  
  17.   
  18.     assertNull(MyCacheManager.getInstance().get("Test", key));  
  19. }  
  1. public void testEventListener()  
  2. {  
  3.     String key = "person";  
  4.     Person person = new Person("lcl"100);  
  5.     MyCacheManager.getInstance().put("Test", key, person);  
  6.     Person p = (Person) MyCacheManager.getInstance().get("Test", key);  
  7.   
  8.     try  
  9.     {  
  10.         Thread.sleep(10000);  
  11.     }  
  12.     catch (InterruptedException e)  
  13.     {  
  14.         // TODO Auto-generated catch block  
  15.         e.printStackTrace();  
  16.     }  
  17.   
  18.     assertNull(MyCacheManager.getInstance().get("Test", key));  
  19. }  

 

   
    根據配置, 該緩存對象生命期只有2分鐘, 在Thread.sleep(10000)期間, 該緩存元素將過期被銷燬, 在銷燬前, 觸發notifyElementExpired事件.
   
二 Ehcache配置文件
 以如下配置爲例說明:

Xml代碼 複製代碼 收藏代碼
  1. <cache name="CACHE_FUNC"   
  2. maxElementsInMemory="2"   
  3. eternal="false"   
  4. timeToIdleSeconds="10"   
  5. timeToLiveSeconds="20"  
  6. overflowToDisk="true"   
  7. diskPersistent="true"   
  8. diskExpiryThreadIntervalSeconds="120"  />  
  1. <cache name="CACHE_FUNC"   
  2. maxElementsInMemory="2"   
  3. eternal="false"   
  4. timeToIdleSeconds="10"   
  5. timeToLiveSeconds="20"  
  6. overflowToDisk="true"   
  7. diskPersistent="true"   
  8. diskExpiryThreadIntervalSeconds="120"  />  

 

maxElementsInMemory :cache 中最多可以存放的元素的數量。如果放入cache中的元素超過這個數值,有兩種情況:
1. 若overflowToDisk的屬性值爲true,會將cache中多出的元素放入磁盤文件中。
2. 若overflowToDisk的屬性值爲false,會根據memoryStoreEvictionPolicy的策略替換cache中原有的元素。

eternal :是否永駐內存。如果值是true,cache中的元素將一直保存在內存中,不會因爲時間超時而丟失,所以在這個值爲true的時候,timeToIdleSeconds和timeToLiveSeconds兩個屬性的值就不起作用了。


 3. timeToIdleSeconds :訪問這個cache中元素的最大間隔時間。如果超過這個時間沒有訪問這個cache中的某個元素,那麼這個元素將被從cache中清除。


4. timeToLiveSeconds : cache中元素的生存時間。意思是從cache中的某個元素從創建到消亡的時間,從創建開始計時,當超過這個時間,這個元素將被從cache中清除。


5. overflowToDisk :溢出是否寫入磁盤。系統會根據標籤<diskStore path="java.io.tmpdir"/> 中path的值查找對應的屬性值,如果系統的java.io.tmpdir的值是 D:\temp,寫入磁盤的文件就會放在這個文件夾下。文件的名稱是cache的名稱,後綴名的data。如:CACHE_FUNC.data。


6. diskExpiryThreadIntervalSeconds  :磁盤緩存的清理線程運行間隔.


7. memoryStoreEvictionPolicy :內存存儲與釋放策略。有三個值:
LRU -least recently used
LFU -least frequently used
FIFO-first in first out, the oldest element by creation time


diskPersistent : 是否持久化磁盤緩存。當這個屬性的值爲true時,系統在初始化的時候會在磁盤中查找文件名爲cache名稱,後綴名爲index的的文件,如CACHE_FUNC.index 。這個文件中存放了已經持久化在磁盤中的cache的index,找到後把cache加載到內存。要想把cache真正持久化到磁盤,寫程序時必須注意,在是用net.sf.ehcache.Cache的void put (Element element)方法後要使用void flush()方法。
 更多說明可看ehcache自帶的ehcache.xml的註釋說明.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章