Saturday, September 18, 2010

Simple Ehcache in Grails

The other day I needed to cache some results from a several remote services within my Grails application. It wasn't critical to that the response from the remote services be "real-time" and it was O.K. if the information was 10 minutes old (but no older). There are so many ways I could have done this within my Grails application, but I turned to EhCache since I was already using it for my Hibernate 2nd level cache.

First thing I needed to do was setup a simple cache. So here is what I added to resources.groovy:

beans = {
simpleRemoteServiceCache(
org.springframework.cache.ehcache.EhCacheFactoryBean) {
timeToLive = 600 // life span in seconds
}
}

Next it was as simple as injecting this new bean into my services and making use of the cache. Here is a quick example of checking the cache, getting from it, and adding to it.

def dataThatMightBeCached
if (simpleRemoteServiceCache.get("theCacheKey")) {
dataThatMightBeCached = simpleRemoteServiceCache.get("theCacheKey").getValue()
} else {
// ... other code to get the data to be cached ...
simpleRemoteServiceCache.put(
new net.sf.ehcache.Element("theCacheKey",
dataThatMightBeCached)
)
}

That just about does it. EhCache handles expiring the content automatically based upon the timeToLive property for us. Pretty simple really. I could have configured the cache even further either in resources.groovy or in ehcache.xml, but the defaults work for my needs right now.

You can find similar examples of using caches on the Ehcache samples page.

2 comments:

  1. Thanks.. worked like a charm...

    ReplyDelete
  2. Does this use in-memory database or store it in physical location? If I restart JVM or server then will it remove the element from cache?

    ReplyDelete