How to integrate Spring cache plugin with Grails
In one of my recent project, i want to cache method output. For implementing method level cache, i have used spring cache. For implement Spring cache, we can use grails cache plugin.
It’s very easy to integrate cache plugin with grails.
1. Add following plugin dependency in BuildConfig.groovy.
[groovy]compile ":springcache:1.3.1"
[/groovy]
2. We need to define the caches in resource.groovy. Use below mention code to create cache in resources.groovy.
[groovy]
studentCache(EhCacheFactoryBean) { bean ->
cacheManager = ref("springcacheCacheManager")
cacheName = "studentCache"
memoryStoreEvictionPolicy = "LRU"
}
[/groovy]
EhCacheFactoryBean – Pre define class of the spring
studentCache – Cache name
3. Add following codes in Config.groovy file to enable cache.
[groovy]
springcache {
defaults {
eternal = false
diskPersistent = false
}
caches {
studentCache {
memoryStoreEvictionPolicy = "LRU"
ttl=1000
}
}
}
[/groovy]
We need to mention the cache name that we want to enable. We can enable multiple cache.
4. Add @Cacheable annotation above method that you want to cache.
[groovy]
@Cacheable(cache="studentCache")
Student showStudent(long id){
return Student.get(id)
}
[/groovy]
@Cacheable – We need to pass cache name
But one thing we need to ensure, the class in which we are implementing the cache, it should be managed by spring or grails.
Run server, hit the url, you can see our method output is cached.
Hope so this code will work for you 🙂
To know more about Cache, you can take the reference by using below link.
http://grails.org/plugin/springcache