Wednesday, October 7, 2009

JCache in App Engine and Grails

Caching is a great way to improve performance in any application, the less hits to the db for common tasks the greater the performance gain.

And here's how to do so in Java on Google's App Engine and Grails.

Google exposes their memcache caching system via the JCache interface

first of all you may wanna start with the javadocs here.

Since CacheManager is a singleton you can save some code by exposing it as a bean.
in resources.groovy:
cacheManager(javax.cache.CacheManager){
 it.factoryMethod = "getInstance"
}


Now you will need to initialize the cache, this has to be done only once so i do it in Bootstrap.groovy


class BootStrap {
 def cacheManager;
 def init = { servletContext ->
  CacheFactory cacheFactory = cacheManager.getCacheFactory();
  def cache = cacheFactory.createCache([:]);
  cacheManager.registerCache("cache",cache);
 }
}

See below for a practical example of using the cache:

class ForumController {
 def entityManager;
 def list = {
  def cache = cacheManager.getCache("cache")
  def forums;
  if(cache.get("allForums")){
   forums = cache.get("allForums");
  }
  else{
   forums = //your code to get all forums
   //please note the collect enclosure.
   cache.put("allForums",forums.collect{it});
  }
  ["forums":forums]
 }
}



One small caveat, you can store a collection of objects in the cache but it will need to be a ArrayList, so:
cache.put("allForums",Forum.list())
will not work, you will have to do
cache.put("allForums",Forum.list().collect{it})

No comments:

Post a Comment