EHCache 初步使用指南
寫的比較初級,后續將加入對配置文件,內存/磁盤存儲,優化,虛擬機宕機,日志等的說明
1. EHCache 的特點,系統要求及安裝
是一個純Java ,過程中(也可以理解成插入式)緩存實現
Hibernate2.1,Spring支持EHcache嵌入,自我感覺Hibernate2.1 + EHCache 很過癮。。(測試結果比Hibernate+JCS 好多了)
支持多CPU服務器
其版本發布前進行了產品級測試
支持:運行環境jdk1.2到5版本(源代碼編譯需1.4或1.5 版本)
jdk1.4和1.5 版本,需加入apache 的 commons-logging類庫 http://jakarta.apache.org/commons/logging.html
jdk1.2和1.3 版本,需加入commons-collections 2.1 版本 http://jakarta.apache.org/commons/collections.html
和 xerces (xml-apis.jar and xercesImpl.jar), 2.5 版本 http://xml.apache.org/xerces2-j/
如果運行環境為IBM JDK1.4版本上的IBM Websphere 5.1,也需加入 commons-collections 類庫(如需要)
單獨安裝Ehcache ,需把ehcache-X.X.jar 和相關類庫方到classpath中。
如項目已安裝了Hibernate2.1 ,則不需要做什么。。直接可以使用Ehcache
Cache 存儲方式 :內存或磁盤
2. 單獨使用 EHCache
使用CacheManager 創建并管理Cache
使用默認配置文件創建
CacheManager manager = CacheManager.create();
使用指定配置文件創建
CacheManager manager = CacheManager.create("src/config/ehcache.xml");
從classpathq找尋配置文件并創建
URL url = getClass().getResource("/anothername.xml");
CacheManager manager = CacheManager.create(url);
通過輸入流創建
InputStream fis = new FileInputStream(new File("src/config/ehcache.xml").getAbsolutePath());
try {
manager = CacheManager.create(fis);
} finally {
fis.close();
}
卸載CacheManager ,關閉Cache
manager.shutdown();
使用Caches
取得配置文件中預先 定義的sampleCache1設置,生成一個Cache
Cache cache = manager.getCache("sampleCache1");
設置一個名為test 的新cache,test屬性為默認
CacheManager manager = CacheManager.create();
manager.addCache("test");
設置一個名為test 的新cache,并定義其屬性
CacheManager manager = CacheManager.create();
Cache cache = new Cache("test", 1, true, false, 5, 2);
manager.addCache(cache);
往cache中加入元素
Element element = new Element("key1", "value1");
cache.put(new Element(element);
從cache中取得元素
Element element = cache.get("key1");
3. 在 Hibernate 中運用EHCache
hibernate.cfg.xml中需設置如下:
2.1版本加入
net.sf.ehcache.hibernate.Provider
2.1以下版本加入
net.sf.hibernate.cache.EhCache
在 Hibernate 映射文件的每個需要Cache的Domain中
name="com.somecompany.someproject.domain.Country"
table="ut_Countries"
dynamic-update="false"
dynamic-insert="false"
>
...
加入類似如下格式信息:
比如:
然后在ehcache.xml中加入
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="false"