Grails cache-ehcache插件和TTL值

时间:2012-09-13 21:25:54

标签: grails ehcache

任何人都可以确认是否有TTL设置,例如可以使用带有ehcache扩展名的grails缓存插件设置timeToLiveSeconds吗?

基本插件的文档明确声明不支持TTL,但ehcache扩展名提到了这些值。到目前为止,我没有成功为我的缓存设置TTL值:

grails.cache.config = {
    cache {
        name 'messages'
        maxElementsInMemory 1000
        eternal false
        timeToLiveSeconds 120
        overflowToDisk false
        memoryStoreEvictionPolicy 'LRU'
    }
}

@Cacheable('messages')
def getMessages()

然而,邮件仍然无限期缓存。我可以使用@CacheEvict注释手动刷新缓存,但我希望在使用ehcache扩展时支持TTL。

由于

3 个答案:

答案 0 :(得分:5)

是的,cache-ehcache插件肯定支持TTL以及EhCache本机支持的所有缓存配置属性。如文档中所述,基本缓存插件实现了一个不支持TTL的简单内存缓存,但Cache DSL将通过任何未知配置设置传递给底层缓存提供程序。

您可以通过将以下内容添加到Config.groovyCacheConfig.groovy来配置EhCache设置:

grails.cache.config = {
    cache {
        name 'mycache'
    }

    //this is not a cache, it's a set of default configs to apply to other caches
    defaults {
        eternal false
        overflowToDisk true
        maxElementsInMemory 10000
        maxElementsOnDisk 10000000
        timeToLiveSeconds 300
        timeToIdleSeconds 0
    }
}

您可以在运行时验证缓存设置,如下所示:

grailsCacheManager.cacheNames.each { 
   def config = grailsCacheManager.getCache(it).nativeCache.cacheConfiguration
   println "timeToLiveSeconds: ${config.timeToLiveSeconds}"
   println "timeToIdleSeconds: ${config.timeToIdleSeconds}"
}

有关其他缓存属性,请参阅EhCache javadoc for CacheConfiguration。您还可以通过记录grails.plugin.cachenet.sf.ehcache来启用详细的缓存调试日志记录。

请注意,Grails缓存插件实现了自己的缓存管理器,该管理器与本机EhCache缓存管理器不同且独立。如果您已直接配置EhCache(使用ehcache.xml或其他方法),则这些缓存将与Grails插件管理的缓存分开运行。

注意:在旧版本的Cache-EhCache插件中确实存在一个错误,其中TTL设置未正确设置且对象在一年内到期;这已在Grails-Cache-Ehcache 1.1中修复。

答案 1 :(得分:0)

ehcache核心插件支持TTL属性。你是如何安装插件的?对于我的项目,我只有:

compile ":cache-ehcache:1.0.0"

在插件关闭中的BuildConfig.groovy中。由于此插件依赖于核心grails缓存插件,因此您无需声明它。

答案 2 :(得分:0)

我可以使用grails-app/conf/BootStrap.groovy脚本解决此问题,在启动时覆盖配置。

例如,这是一个脚本,用于覆盖名为“mycache”的缓存的 60秒的默认时间:

class BootStrap {

    def grailsCacheManager

    def init = { servletContext ->
        grailsCacheManager.getCache("mycache").nativeCache
                        .cacheConfiguration.timeToLiveSeconds = 60
    }
    def destroy = {
    }
}
相关问题