2013-04-25 75 views
0

我想將Ehcache包含在託管在Tomcat中的Java Web應用程序中。我想要做的是檢查我的緩存中是否有密鑰,如果密鑰存在,則檢索它,如果不存在,則將其添加到緩存中供以後檢索(就像memcached使用場景一樣)。Ehcache with tomcat簡單示例

我搜索了文檔,找不到有關如何實現這個簡單示例的有用信息。我只發現我需要將ehcache-core.jar和slf4j * .jar與ehcache.xml一起放入我的類路徑中。那又怎麼樣?我可以在示例中看到一個Ehcache緩存對象 - 但我應該在哪裏實例化以便可以從我的servlet/JSP訪問?另外,你能推薦一個非常簡單的緩存配置來放入ehcache.xml嗎?是默認的

 
    <defaultCache 
      maxEntriesLocalHeap="0" 
      eternal="false" 
      timeToIdleSeconds="1200" 
      timeToLiveSeconds="1200"> 
    </defaultCache> 

好嗎?

回答

4

這樣做

CacheManager.getInstance().addCache("xyz"); // creates a cache called xyz. 

Cache xyz = CacheManager.getInstance().getCache("xyz"); 

xyz.put(new Element("key", new Person())); 
Element e = xyz.get("key"); 
Person p = (Person) e.getObjectValue(); 

沒有與高速緩存更好的發揮優雅的方式。參考http://ehcache.org/documentation/code-samples。還要檢查彈簧與它的整合情況。

+0

我也用這個答案http://stackoverflow.com/questions/6206996/tomcat-java-servlet-initialize-class-on-application-startup初始化緩存。謝謝 – Serafeim 2013-04-25 10:19:09