grails中的缓存方法

Caching Methods in grails

我正在寻找一种方法来缓存我在 Grails 中的某些方法的 return 值。我发现插件 ehcache (https://grails.org/plugin/cache-ehcache) 看起来很不错。

但我的示例无法正常工作。我想使用@Cachable 表示法。 我在 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
    }
}

我在控制器中的方法:

@Cacheable('inlinecache')
def inlineCache() {
    return new Date()
}

我总是得到实际日期。我预计该值将持续 30 秒。我做错了什么?

此致, 彼得

您如何调用 inlineCache 方法?

如果您从同一个 class 中调用它,您实际上需要从 Spring 应用程序上下文中获取对服务的引用,并通过它调用该方法,而不是而不是直接调用它。这是因为 Spring 需要拦截您的方法调用,如果您直接从同一个 class.

中调用该方法,它将无法拦截

更新:

如果您想从同一个服务中调用您的缓存方法,您需要按照以下步骤做一些事情:

class MyService {
    String myMethod(String argument) {
        return grailsApplication.mainContext.myService.myMethodCacheable(argument);
    }

    @Cacheable(value="myCacheName")
    String myMethodCacheable(String argument) {          
        return ""
    }
}

所以 myMethod 只是从 spring 应用程序上下文中获取对 MyService 的引用,并委托给其中的 myMethodCacheable() 实现。这意味着我可以从 MyService 中调用 myMethod 并从缓存中取回值(如果存在)。