martedì 17 maggio 2011

SpringCache custom cache resolver & Acegi plugin

Today's snippet is derived from excellent SpringCache plugin documentation, I had to resolve my cache against a property of currently logged user in a sort of multitenancy, so I had to define a custom CacheResolver in src/groovy:

import grails.plugin.springcache.CacheResolver

class CustomCacheResolver implements CacheResolver {
 def authenticateService
 
  String resolveCacheName(String baseName) {
   def user = authenticateService.principal().domainClass
   user = User.get(user.id)
   def bancheIds = user.banche*.getId().sort().join("_")
   "${baseName}-banche-${bancheIds}"
  }
}

and then wire authenticateService in resources.groovy:

customCacheResolver(CustomCacheResolver) {
  authenticateService = ref("authenticateService")
 }

now it can be referenced from SpringCache annotations:

@CacheFlush(caches = "categorieCache", cacheResolver = "customCacheResolver")

and every tenant (defined by banche collection identifiers) has its cache.

Note that I used Acegi plugin, which now is discontinued, but I think the same could be obtained with SpringSecurity plugin also. Just wire springSecurityService and resolve current logged user from it with getCurrentUser().

Nessun commento: