ehcache常用API整理
鑑於csdn的blog的不穩定, 及混亂的編輯器, 和無上傳功能, 遂決定徹底投誠javaeye的blog.
數月前整理的一個東西, 作為cache的掃盲文件.參考了它的官方文件.
對ehcache感興趣的兄臺可以參考.
附件為eclipse專案, 直接匯入, 執行test目錄下的junit testcase, 可一目瞭然.
一 ehcache API:
1: Using the CacheManager
1.1所有ehcache的使用, 都是從 CacheManager. 開始的.
有多種方法建立CacheManager例項:
- //Create a singleton CacheManager using defaults, then list caches.
- CacheManager.getInstance()
- //Create a singleton CacheManager using defaults, then list caches.
- CacheManager.getInstance()
或者:
- //Create a CacheManager instance using defaults, then list caches.
- CacheManager manager = new CacheManager();
- String[] cacheNames = manager.getCacheNames();
- //Create a CacheManager instance using defaults, then list caches.
- CacheManager manager = new CacheManager();
- String[] cacheNames = manager.getCacheNames();
如果需要從指定配置檔案建立 CacheManager:
- Create two CacheManagers, each with a different configuration, and list the caches in each.
- CacheManager manager1 = new
- CacheManager manager2 = new CacheManager("src/config/ehcache2.xml");
- String[] cacheNamesForManager1 = manager1.getCacheNames();
- String[] cacheNamesForManager2 = manager2.getCacheNames();
- Create two CacheManagers, each with a different configuration, and list the caches in each.
- CacheManager manager1 = new CacheManager("src/config/ehcache1.xml");
- CacheManager manager2 = new CacheManager("src/config/ehcache2.xml");
- String[] cacheNamesForManager1 = manager1.getCacheNames();
- String[] cacheNamesForManager2 = manager2.getCacheNames();
1.2 Adding and Removing Caches Programmatically
手動建立一個cache, 而不是通過配置檔案:
- //creates a cache called testCache, which
- //will be configured using defaultCache from the configuration
- CacheManager singletonManager = CacheManager.create();
- singletonManager.addCache("testCache");
- Cache test = singletonManager.getCache("testCache");
- //creates a cache called testCache, which
- //will be configured using defaultCache from the configuration
- CacheManager singletonManager = CacheManager.create();
- singletonManager.addCache("testCache");
- Cache test = singletonManager.getCache("testCache");
或者:
Java程式碼- //Create a Cache and add it to the CacheManager, then use it. Note that Caches are not usable until they have
- //been added to a CacheManager.
- publicvoid testCreatCacheByProgram()
- {
- CacheManager singletonManager = CacheManager.create();
- Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
- singletonManager.addCache(memoryOnlyCache);
- Cache testCache = singletonManager.getCache("testCache");
- assertNotNull(testCache);
- }
- //Create a Cache and add it to the CacheManager, then use it. Note that Caches are not usable until they have
- //been added to a CacheManager.
- publicvoid testCreatCacheByProgram()
- {
- CacheManager singletonManager = CacheManager.create();
- Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
- singletonManager.addCache(memoryOnlyCache);
- Cache testCache = singletonManager.getCache("testCache");
- assertNotNull(testCache);
- }
手動移除一個cache:
- //Remove cache called sampleCache1
- CacheManager singletonManager = CacheManager.create();
- singletonManager.removeCache("sampleCache1");
- //Remove cache called sampleCache1
- CacheManager singletonManager = CacheManager.create();
- singletonManager.removeCache("sampleCache1");
1.3 Shutdown the CacheManager
ehcache應該在使用後關閉, 最佳實踐是在code中顯式呼叫:
- //Shutdown the singleton CacheManager
- CacheManager.getInstance().shutdown();
- //Shutdown the singleton CacheManager
- CacheManager.getInstance().shutdown();
2 Using Caches
比如我有這樣一個cache:
- <cachename="sampleCache1"maxElementsInMemory="10000"
- maxElementsOnDisk="1000"eternal="false"overflowToDisk="true"
- diskSpoolBufferSizeMB="20"timeToIdleSeconds="300"
- timeToLiveSeconds="600"memoryStoreEvictionPolicy="LFU"/>
- <cachename="sampleCache1"maxElementsInMemory="10000"
- maxElementsOnDisk="1000"eternal="false"overflowToDisk="true"
- diskSpoolBufferSizeMB="20"timeToIdleSeconds="300"
- timeToLiveSeconds="600"memoryStoreEvictionPolicy="LFU"/>
2.1 Obtaining a reference to a Cache
獲得該cache的引用:
- String cacheName = "sampleCache1";
- CacheManager manager = new CacheManager("src/ehcache1.xml");
- Cache cache = manager.getCache(cacheName);
- String cacheName = "sampleCache1";
- CacheManager manager = new CacheManager("src/ehcache1.xml");
- Cache cache = manager.getCache(cacheName);
2.2 Performing CRUD operations
下面的程式碼演示了ehcache的增刪改查:
- publicvoid testCRUD()
- {
- String cacheName = "sampleCache1";
- CacheManager manager = new CacheManager("src/ehcache1.xml");
- Cache cache = manager.getCache(cacheName);
- //Put an element into a cache
- Element element = new Element("key1", "value1");
- cache.put(element);
- //This updates the entry for "key1"
- cache.put(new Element("key1", "value2"));
- //Get a Serializable value from an element in a cache with a key of "key1".
- element = cache.get("key1");
- Serializable value = element.getValue();
- //Get a NonSerializable value from an element in a cache with a key of "key1".
- element = cache.get("key1");
- assertNotNull(element);
- Object valueObj = element.getObjectValue();
- assertNotNull(valueObj);
- //Remove an element from a cache with a key of "key1".
- assertNotNull(cache.get("key1"));
- cache.remove("key1");
- assertNull(cache.get("key1"));
- }
- publicvoid testCRUD()
- {
- String cacheName = "sampleCache1";
- CacheManager manager = new CacheManager("src/ehcache1.xml");
- Cache cache = manager.getCache(cacheName);
- //Put an element into a cache
- Element element = new Element("key1", "value1");
- cache.put(element);
- //This updates the entry for "key1"
- cache.put(new Element("key1", "value2"));
- //Get a Serializable value from an element in a cache with a key of "key1".
- element = cache.get("key1");
- Serializable value = element.getValue();
- //Get a NonSerializable value from an element in a cache with a key of "key1".
- element = cache.get("key1");
- assertNotNull(element);
- Object valueObj = element.getObjectValue();
- assertNotNull(valueObj);
- //Remove an element from a cache with a key of "key1".
- assertNotNull(cache.get("key1"));
- cache.remove("key1");
- assertNull(cache.get("key1"));
- }
2.3 Disk Persistence on demand
- //sampleCache1 has a persistent diskStore. We wish to ensure that the data //and index are written immediately.
- publicvoid testDiskPersistence()
- {
- String cacheName = "sampleCache1";
- CacheManager manager = new CacheManager("src/ehcache1.xml");
- Cache cache = manager.getCache(cacheName);
- for (int i = 0; i < 50000; i++)
- {
- Element element = new Element("key" + i, "myvalue" + i);
- cache.put(element);
- }
- cache.flush();
- Log.debug("java.io.tmpdir = " + System.getProperty("java.io.tmpdir"));
- }
- //sampleCache1 has a persistent diskStore. We wish to ensure that the data //and index are written immediately.
- publicvoid testDiskPersistence()
- {
- String cacheName = "sampleCache1";
- CacheManager manager = new CacheManager("src/ehcache1.xml");
- Cache cache = manager.getCache(cacheName);
- for (int i = 0; i < 50000; i++)
- {
- Element element = new Element("key" + i, "myvalue" + i);
- cache.put(element);
- }
- cache.flush();
- Log.debug("java.io.tmpdir = " + System.getProperty("java.io.tmpdir"));
- }
備註: 持久化到硬碟的路徑由虛擬機器引數"Java.io.tmpdir"決定.
例如, 在windows中, 會在此路徑下
C:\Documents and Settings\li\Local Settings\Temp
在linux中, 通常會在: /tmp 下
2.4 Obtaining Cache Sizes
以下程式碼演示如何獲得cache個數:
- publicvoid testCachesizes()
- {
- long count = 5;
- String cacheName = "sampleCache1";
- CacheManager manager = new CacheManager("src/ehcache1.xml");
- Cache cache = manager.getCache(cacheName);
- for (int i = 0; i < count; i++)
- {
- Element element = new Element("key" + i, "myvalue" + i);
- cache.put(element);
- }
- //Get the number of elements currently in the Cache.
- int elementsInCache = cache.getSize();
- assertTrue(elementsInCache == 5);
- //Cache cache = manager.getCache("sampleCache1");
- long elementsInMemory = cache.getMemoryStoreSize();
- //Get the number of elements currently in the DiskStore.
- long elementsInDiskStore = cache.getDiskStoreSize();
- assertTrue(elementsInMemory + elementsInDiskStore == count);
- }
- publicvoid testCachesizes()
- {
- long count = 5;
- String cacheName = "sampleCache1";
- CacheManager manager = new CacheManager("src/ehcache1.xml");
- Cache cache = manager.getCache(cacheName);
- for (int i = 0; i < count; i++)
- {
- Element element = new Element("key" + i, "myvalue" + i);
- cache.put(element);
- }
- //Get the number of elements currently in the Cache.
- int elementsInCache = cache.getSize();
- assertTrue(elementsInCache == 5);
- //Cache cache = manager.getCache("sampleCache1");
- long elementsInMemory = cache.getMemoryStoreSize();
- //Get the number of elements currently in the DiskStore.
- long elementsInDiskStore = cache.getDiskStoreSize();
- assertTrue(elementsInMemory + elementsInDiskStore == count);
- }
3: Registering CacheStatistics in an MBeanServer
ehCache 提供jmx支援:
- CacheManager manager = new CacheManager();
- MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
- ManagementService.registerMBeans(manager, mBeanServer, false, false, false, true);
- CacheManager manager = new CacheManager();
- MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
- ManagementService.registerMBeans(manager, mBeanServer, false, false, false, true);
把該程式打包, 然後:
- java -Dcom.sun.management.jmxremote -jar 程式名.jar
- java -Dcom.sun.management.jmxremote -jar 程式名.jar
再到javahome/bin中執行jconsole.exe, 便可監控cache.
4. 使用者可以自定義處理cacheEventHandler, 處理諸如元素放入cache的各種事件(放入,移除,過期等事件)
只需三步:
4.1 在cache配置中, 增加cacheEventListenerFactory節點.
- <cache name="Test" maxElementsInMemory="1" eternal="false"
- overflowToDisk="true" timeToIdleSeconds="1" timeToLiveSeconds="2"
- diskPersistent="false" diskExpiryThreadIntervalSeconds="1"
- memoryStoreEvictionPolicy="LFU">
- <cacheEventListenerFactory class="co.ehcache.EventFactory" />
- </cache>
- <cache name="Test" maxElementsInMemory="1" eternal="false"
- overflowToDisk="true" timeToIdleSeconds="1" timeToLiveSeconds="2"
- diskPersistent="false" diskExpiryThreadIntervalSeconds="1"
- memoryStoreEvictionPolicy="LFU">
- <cacheEventListenerFactory class="co.ehcache.EventFactory" />
- </cache>
4.2: 編寫EventFactory, 繼承CacheEventListenerFactory:
Java程式碼- publicclass EventFactory extends CacheEventListenerFactory
- {
- @Override
- public CacheEventListener createCacheEventListener(Properties properties)
- {
- // TODO Auto-generated method stub
- returnnew CacheEvent();
- }
- }
- publicclass EventFactory extends CacheEventListenerFactory
- {
- @Override
- public CacheEventListener createCacheEventListener(Properties properties)
- {
- // TODO Auto-generated method stub
- returnnew CacheEvent();
- }
- }
4.3 編寫 class: CacheEvent, 實現 CacheEventListener 介面:
- publicclass CacheEvent implements CacheEventListener
- {
- publicvoid dispose()
- {
- log("in dispose");
- }
- publicvoid notifyElementEvicted(Ehcache cache, Element element)
- {
- // TODO Auto-generated method stub
- log("in notifyElementEvicted" + element);
- }
- publicvoid notifyElementExpired(Ehcache cache, Element element)
- {
- // TODO Auto-generated method stub
- log("in notifyElementExpired" + element);
- }
- publicvoid notifyElementPut(Ehcache cache, Element element) throws CacheException
- {
- // TODO Auto-generated method stub
- log("in notifyElementPut" + element);
- }
- publicvoid notifyElementRemoved(Ehcache cache, Element element) throws CacheException
- {
- // TODO Auto-generated method stub
- log("in notifyElementRemoved" + element);
- }
- publicvoid notifyElementUpdated(Ehcache cache, Element element) throws CacheException
- {
- // TODO Auto-generated method stub
- log("in notifyElementUpdated" + element);
- }
- publicvoid notifyRemoveAll(Ehcache cache)
- {
- // TODO Auto-generated method stub
- log("in notifyRemoveAll");
- }
- public Object clone() throws CloneNotSupportedException
- {
- returnsuper.clone();
- }
- privatevoid log(String s)
- {
- Log.debug(s);
- }
- }
- publicclass CacheEvent implements CacheEventListener
- {
- publicvoid dispose()
- {
- log("in dispose");
- }
- publicvoid notifyElementEvicted(Ehcache cache, Element element)
- {
- // TODO Auto-generated method stub
- log("in notifyElementEvicted" + element);
- }
- publicvoid notifyElementExpired(Ehcache cache, Element element)
- {
- // TODO Auto-generated method stub
- log("in notifyElementExpired" + element);
- }
- publicvoid notifyElementPut(Ehcache cache, Element element) throws CacheException
- {
- // TODO Auto-generated method stub
- log("in notifyElementPut" + element);
- }
- publicvoid notifyElementRemoved(Ehcache cache, Element element) throws CacheException
- {
- // TODO Auto-generated method stub
- log("in notifyElementRemoved" + element);
- }
- publicvoid notifyElementUpdated(Ehcache cache, Element element) throws CacheException
- {
- // TODO Auto-generated method stub
- log("in notifyElementUpdated" + element);
- }
- publicvoid notifyRemoveAll(Ehcache cache)
- {
- // TODO Auto-generated method stub
- log("in notifyRemoveAll");
- }
- public Object clone() throws CloneNotSupportedException
- {
- returnsuper.clone();
- }
- privatevoid log(String s)
- {
- Log.debug(s);
- }
- }
現在可以編寫測試程式碼:
Java程式碼- publicvoid testEventListener()
- {
- String key = "person";
- Person person = new Person("lcl", 100);
- MyCacheManager.getInstance().put("Test", key, person);
- Person p = (Person) MyCacheManager.getInstance().get("Test", key);
- try
- {
- Thread.sleep(10000);
- }
- catch (InterruptedException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- assertNull(MyCacheManager.getInstance().get("Test", key));
- }
- publicvoid testEventListener()
- {
- String key = "person";
- Person person = new Person("lcl", 100);
- MyCacheManager.getInstance().put("Test", key, person);
- Person p = (Person) MyCacheManager.getInstance().get("Test", key);
- try
- {
- Thread.sleep(10000);
- }
- catch (InterruptedException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- assertNull(MyCacheManager.getInstance().get("Test", key));
- }
根據配置, 該快取物件生命期只有2分鐘, 在Thread.sleep(10000)期間, 該快取元素將過期被銷燬, 在銷燬前, 觸發notifyElementExpired事件.
二 Ehcache配置檔案
以如下配置為例說明:
- <cachename="CACHE_FUNC"
- maxElementsInMemory="2"
- eternal="false"
- timeToIdleSeconds="10"
- timeToLiveSeconds="20"
- overflowToDisk="true"
- diskPersistent="true"
- diskExpiryThreadIntervalSeconds="120"/>
- <cachename="CACHE_FUNC"
- maxElementsInMemory="2"
- eternal="false"
- timeToIdleSeconds="10"
- timeToLiveSeconds="20"
- overflowToDisk="true"
- diskPersistent="true"
- 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的註釋說明.