views:

212

answers:

3

Hi,

I'd like to use memcached to cache the response produced by my controllers. The controllers themselves are Grails controllers, but there's nothing really Grails-specific about the problem. If I could figure out how to solve this problem in a Spring MVC, Struts (or similar) application, I should easily be able to migrate the solution to Grails.

Ideally, I'd like to identify the controller methods that are eligible for caching using Java annotations. Is anyone aware of an existing solution for this problem? I should emphasise that I'm not interested in using any caching technology other than memcached.

Thanks, Don

A: 

Would something like this do the trick? http://code.google.com/p/simple-spring-memcached/

braveterry
No, it doesn't seem to provide any support for caching controller output
Don
+2  A: 

The Simple Spring Memcached library the previous poster linked to would actually accomplish what you need to do. It doesn't limit itself to just DAO methods. You could annotate a controller method to cache it's response just as easily as annotating a DAO method.

So, if you have a Controller named SimpleController and you wanted to cache the response of that controller, you could do the following

public class SimpleController implements Controller {
  @ReadThroughSingleCache(namespace = "SimpleController", keyIndex = 0, expiration = 3600)
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
     return new ModelAndView("index")
  }

This will cache the response of the controller in Memcached for an hour and any request that comes in that matches the same request will return the cached response.

Aaron
+1  A: 

Aaron, braveterry,

Thanks for suggesting my project: http://code.google.com/p/simple-spring-memcached/

Don, Aaron is correct that SSM is not limited to DAO methods, however there are a few caveats for his example:

  1. I don't think HttpServletRequest's toString() method would produce a good key
  2. You would need to make sure that ModelAndView is Serializable
  3. That being said, there's no reason you can't delegate to another bean that has an appropriate signature

Here's some code as an example:

public class SimpleController implements Controller {
      private BeanWithAnnotatedMethod bean; // Injected resource
      public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
         Object keyObject = Helper.generateAppropriateKey(request);
         String result = bean.annotatedMethod(keyObject);
         return new ModelAndView(result)
      }
Nelz