【问题标题】:@Cachable on methods without input parameters?@Cachable 在没有输入参数的方法上?
【发布时间】:2018-07-31 00:31:24
【问题描述】:

@org.springframework.cache.annotation.Cachable 注释有问题:

@Bean
public ConcurrentMapCache cache() {
    return new ConcurrentMapCache(CACHE);
}

@Cacheable(CACHE)
public String getApi() {
    return "api";
}

@Cacheable(CACHE)
public String getUrl() {
    return "url";
}

用法:

assertEquals("api", service.getApi()); //OK
assertEquals("url", service.getUrl()); //FAILURE. this returns also "api"

那么,为什么@Cachable 不通过方法名创建缓存结果如果方法签名不包含任何输入参数?

【问题讨论】:

    标签: java spring caching spring-cache


    【解决方案1】:

    试试这个

    @Cacheable(value = CACHE, key = "#root.method.name")
    

    你需要告诉 spring 使用方法名作为键。您可以为此使用 SPEL。这是doc 以及其他各种选项。

    【讨论】:

    • 虽然这行得通 - 这不是违反直觉吗?我的意思是,为什么春天的家伙曾经想过在没有参数的方法上添加 @Cachable 应该这样工作?
    • @membersound 这确实违反直觉,即使他们的示例也没有考虑到这一点。我今天浪费了一些时间,直到我阅读了文档,找到了那条特殊的行:This approach works only for methods that are guaranteed to return the same output (result) for a given input (or arguments) no matter how many times it is executed.
    【解决方案2】:

    您可以使用两个不同名称的缓存:

    @Bean
    public ConcurrentMapCache cache() {
        return new ConcurrentMapCache(CACHE_API, CACHE_URL);
    }
    @Cacheable(CACHE_API)
    public String getApi() {
        return "api";
    }
    
    @Cacheable(CACHE_URL)
    public String getUrl() {
        return "url";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      • 2019-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多