I am looking for a way to cache the return values of some of my methods in Grails. I found the plugin ehcache (https://grails.org/plugin/cache-ehcache) which looks very good.
But I can't get my example to work. I want to use @Cachable notation. My configuration in Config.groovy:
grails{
cache {
enabled = true
ehcache {
reloadable = false
}
}
}
grails.cache.config = {
cache {
name 'inlinecache'
eternal false
enabled true
overflowToDisk true
maxElementsInMemory 10000
maxElementsOnDisk 10000000
timeToLiveSeconds 30
}
}
My method in Controller:
@Cacheable('inlinecache')
def inlineCache() {
return new Date()
}
I always get the actual date. I expect the value to last for 30 seconds. What am I doing wrong?
Best regards, Peter
How are you calling your inlineCache
method?
If you're calling it from within the same class, you'll actually need to get a reference to the service from the Spring application context, and invoke the method through that rather than calling it directly. The reason for this is because Spring needs to intercept your method invocation and it won't be able to if you call that method directly from within the same class.
UPDATE:
If you want to call your cached method from within the same service, you'll need to do something along these lines:
class MyService {
String myMethod(String argument) {
return grailsApplication.mainContext.myService.myMethodCacheable(argument);
}
@Cacheable(value="myCacheName")
String myMethodCacheable(String argument) {
return ""
}
}
So myMethod
just gets a reference to MyService
from the spring application context and delegates to the myMethodCacheable()
implementation inside there. This means that I can call myMethod
from within MyService
and get back the value from the cache if it is there.