Grails缓存-ehcache插件和TTL值

5

有人能否证实使用 ehcache 扩展的 grails 缓存插件是否可以设置 TTL 设置,例如 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。谢谢。

这个问题很久以前就被问过了,但请参见https://jira.grails.org/browse/GPCACHEEHCACHE-6。 - Ken Liu
@Ken,那个链接现在已经失效了。 - GreenGiant
3个回答

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 中已得到修复。

0

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

compile ":cache-ehcache:1.0.0"

在BuildConfig.groovy文件的plugins闭包中。由于该插件依赖于核心Grails缓存插件,因此您无需声明它。


0

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

例如,以下是用于将名为“mycache”的缓存的默认生存时间覆盖为60秒的脚本:

class BootStrap {

    def grailsCacheManager

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接