How to integrate Spring cache plugin with Grails

25 / Sep / 2012 by Mohit Garg 0 comments

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.

compile ":springcache:1.3.1"

2.  We need to define the caches in resource.groovy. Use below mention code to create cache in resources.groovy.


studentCache(EhCacheFactoryBean) { bean ->
cacheManager = ref("springcacheCacheManager")
cacheName = "studentCache"
memoryStoreEvictionPolicy = "LRU"
}

EhCacheFactoryBean – Pre define class of the spring
studentCache – Cache name

3. Add following codes in Config.groovy file to enable cache.

springcache {
    defaults {
        eternal = false
        diskPersistent = false
    }
    caches {
        studentCache {
            memoryStoreEvictionPolicy = "LRU"
           ttl=1000
        }
    }
}

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.

@Cacheable(cache="studentCache")
    Student showStudent(long id){
        return Student.get(id)
    }

@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

FOUND THIS USEFUL? SHARE IT

Leave a comment -