首页 > 解决方案 > 带有 grails 3 的 eh-cache

问题描述

Ehcache 在我的项目中无法正常工作。我运行 grails 3.3.1 "with org.grails.plugins:cache-ehcache:3.0.0.M1" 并且因为我不知道将 ehcache.xml 文件放在哪里以及文件的外观我试图以编程方式配置 ehcache

我使用从 bootstrap.groovy 运行的方法“initCaches”创建了一个 cacheService

class CacheService {
void initCaches() {       
    CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
        .withCache("sevenSeconds", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10))
            .withExpiry(Expirations.timeToLiveExpiration(Duration.of(7, TimeUnit.SECONDS)))
        )
        .withCache("twentySeconds", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10))
            .withExpiry(Expirations.timeToLiveExpiration(Duration.of(20, TimeUnit.SECONDS)))
        )
        .build()  
    cacheManager.init()
}
}

当我启动应用程序时,控制台说缓存已创建:

2018-06-26 15:47:31.302  INFO --- [           main] org.ehcache.core.EhcacheManager          : Cache 'sevenSeconds' created in EhcacheManager.
2018-06-26 15:47:31.310  INFO --- [           main] org.ehcache.core.EhcacheManager          : Cache 'twentySeconds' created in EhcacheManager.

现在我访问了一个用 @Cacheable("sevenSeconds") 注释的服务方法,然后出现了让我困惑的部分:控制台再次说,缓存已经创建(而不是将结果放入旧的已经出CacheService 创建了一个):

2018-06-26 15:47:31.302  INFO --- [           main] org.ehcache.core.EhcacheManager          : Cache 'sevenSeconds' created in EhcacheManager.

如果我使用相同的参数再次访问该服务,则会返回缓存结果,但 timeToLive 不是 7 秒,就像我在 CacheService 中创建缓存一样。

看起来@Cacheable 没有考虑我在 CacheService 中创建的缓存

有人知道我做错了什么吗?

谢谢

标签: grails3ehcache-3

解决方案


我不知道 Grails 如何管理CacheService以及如何initCaches调用。但是,您CacheManager是一个局部变量。所以我希望它会在initCaches.

@Cacheable可能正在使用其他一些CacheManager. 所以这就是你应该通过使CacheManager创建的 ininitCaches可用于 Grails 预期的约定来解决的问题。


推荐阅读