ehcache可以單獨使用也可以和hibernate、spring等一起使用。
本人今天單獨使用,並做些測試,分享經驗如下,
需要2個包,commons-logging.jar、ehcache-core-2.5.1.jar,最好使用ehcache的高版本,不然會配置文件的某些屬性不可用,如maxElementsInMemory等。這個版本需要commons-logging.jar包。
先配置xml文件,必須要有defaultCache,代碼類似如下,
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.sf.net/ehcache.xsd">
<diskStore path="E:/mytemp" />
<defaultCache
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="10"
timeToLiveSeconds="20"
diskPersistent="false" />
<cache name="requestCache"
maxElementsInMemory="100000"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="180"
timeToLiveSeconds="180"
diskPersistent="false"
memoryStoreEvictionPolicy="LFU" />
<cache name="myCache"
maxElementsInMemory="2"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="180"
timeToLiveSeconds="180"
maxElementsOnDisk="0"
diskPersistent="true"
memoryStoreEvictionPolicy="LFU" />
</ehcache>
diskStore中的 是硬盤存放路勁,有個參數是user.io.dir表示eclipse默認路徑,在document and setting ....的某個子目錄下。
最好寫自己的路徑。
幾個重要屬性,請參考這里。
需要注意的是
當overflowToDisk為true時,在diskStore路勁下生成2個文件,一個是myCache.data和myCache.index,
若diskPersistent 這個屬性如果設置為false,main方法(或web應用關閉)結束后上面2個文件就沒了。
若diskPersistent 為true,則main方法結束后2文件存在
當再次啟動時,程序會加載myCache.index這個文件。
測試方法如下,
public class Test {
public static void main(String[] args) {
// 指定ehcache.xml的位置
String fileName = "F:/myeclipse/workspace/ecache/src/ehcache.xml";
CacheManager manager = new CacheManager(fileName);
// 取出所有的cacheName
String names[] = manager.getCacheNames();
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
Cache cache = manager.getCache("myCache");
System.out.println(cache.getSize());
for(int i=0;i<100000;i++){
cache.put(new Element("key1"+ i , "values1"+i));
}
// cache.flush();
manager.shutdown();
}
}
需要manager.shutdown(),不然要手動關閉