Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best strategy to cache expensive web service call in Grails

Tags:

caching

grails

I have a simple Grails application that needs to make a periodic call to an external web service several times during a user's session (while the use the interface).

I'd like to cache this web service response, but the results from the service change about every few days, so I'd like to cache it for a short time (perhaps daily refreshes).

The Grails cache plugin doesn't appear to support "time to live" implementations so I've been exploring a few possible solutions. I'd like to know what plugin or programatic solution would best solve this problem.

Example:

BuildConfig.groovy

plugins{
    compile ':cache:1.0.0'
}

MyController.groovy

def getItems(){
    def items = MyService.getItems()
    [items: items]
}

MyService.groovy

@Cacheable("itemsCache")
class MyService {
    def getItems() {
        def results

        //expensive external web service call

        return results
    }
}

UPDATE

There were many good options. I decided to go with the plugin approach that Burt suggested. I've included a sample answer with minor changes to above code example to help others out wanting to do something similar. This configuration expires the cache after 24 hours.

BuildConfig.groovy

plugins{
    compile ':cache:1.1.7'
    compile ':cache-ehcache:1.0.1'
}

Config.groovy

grails.cache.config = {
    defaultCache {
        maxElementsInMemory 10000
        eternal false
        timeToIdleSeconds 86400
        timeToLiveSeconds 86400
        overflowToDisk false
        maxElementsOnDisk 0
        diskPersistent false
        diskExpiryThreadIntervalSeconds 120
        memoryStoreEvictionPolicy 'LRU'
     }
 }
like image 255
arcdegree Avatar asked Feb 12 '13 19:02

arcdegree


2 Answers

The core plugin doesn't support TTL, but the Ehcache plugin does. See http://grails-plugins.github.com/grails-cache-ehcache/docs/manual/guide/usage.html#dsl

The http://grails.org/plugin/cache-ehcache plugin depends on http://grails.org/plugin/cache but replaces the cache manager with one that uses Ehcache (so you need both installed)

like image 107
Burt Beckwith Avatar answered Nov 07 '22 08:11

Burt Beckwith


A hack/workaround would be to use a combination of @Cacheable("itemsCache") and @CacheFlush("itemsCache").

Tell the getItems() method to cache the results.

@Cacheable("itemsCache")
def getItems() {
}

and then another service method to flush the cache, which you can call frequently from a Job.

@CacheFlush("itemsCache")
def flushItemsCache() {}
like image 31
uchamp Avatar answered Nov 07 '22 08:11

uchamp