Caching pages using ehcache

When an http request to your /rss page needs 400 milliseconds to complete, it seems obvious that your website could benefit from some caching. Ehcache is a well known cache provider, which most of us know from hibernate. Since we are already “bound” to ehcache, lets see how we can benefit from caching some dynamically generated pages:

web.xml

<filter>
  <filter-name>SimplePageCachingFilter</filter-name>
  <filter-class>net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>SimplePageCachingFilter</filter-name>
  <url-pattern>/rss</url-pattern>
</filter-mapping>

We set up the SimplePageCachingFilter in the web.xml of the web application and map it to one or more url patterns or servlets. All requests to /rss will be intercepted by the SimplePageCachingFilter.

ehcache.xml

<ehcache>
  <diskStore path="java.io.tmpdir" />
  <cache name="SimplePageCachingFilter"
         maxElementsInMemory="0"
         eternal="false"
         timeToIdleSeconds="600"
         timeToLiveSeconds="600"
         overflowToDisk="true"/>        
</ehcache>

We then configure the cache region for pages. We don’t want any elements kept in memory. Everything should be written to disk at the java.io.tmpdir location. The cache expires every 10 minutes.

Now hitting http://example.com/rss (our default rss page) results in a cache miss. The content is being generated from scratch but before returning to the client, the filter stores it locally. The second time we’ll get a cache hit. The content now is being fetched from the cache and its very fast. 10 minutes later this cache element will be invalidated. Note that the default implementation uses the URI together with the query string to calculate the cache key, so /rss?type=news and /rss?type=forum will result in two different cache elements.

3 Responses to “Caching pages using ehcache”

  1. Abishek Says:

    Do you know any link or u have any post about using echcace in ejb projects on netbeans..!

    Please let me know if u know..! iam new to this.

    thanks in advance
    abishek

  2. kenu Says:

    Thanks, google told me that you got an good guidance for ehcache.
    I solved my NullPointer problem.

  3. Paul Says:

    Hi

    Good ooverview on ehcache. what should i do in order to cache a java method which is calling a url?

    thanks
    -p