0

I want to include Ehcache in a Java web application hosted in Tomcat. What I want to do is check my cache for a key and if the key exists then retrieve it, if not then add it to the cache for later retrieval (just like the memcached usage scenario).

I searched the documentation and couldn't find useful information on how to implement this simple example. I only found out that I need to put ehcache-core.jar and slf4j*.jar in my classpath along with ehcache.xml. Then what ? I can see an Ehcache cache object in the examples - but where should I instantiate that in order to be accessible from my servlets / JSPs ? Also, can you recommend a very simple cache configuration to put in ehcache.xml ? Is the default

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

ok ?

Serafeim
  • 14,962
  • 14
  • 91
  • 133

1 Answers1

5

Do something like

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();

There are better elegant ways to play with cache. Refer to http://ehcache.org/documentation/code-samples. Also check spring integration with it.

Bhushan Bhangale
  • 10,921
  • 5
  • 43
  • 71
  • I also used this answer http://stackoverflow.com/questions/6206996/tomcat-java-servlet-initialize-class-on-application-startup to initialize the cache. Thanks – Serafeim Apr 25 '13 at 10:19