【问题标题】:@Cacheable and @CachePut different return type@Cacheable 和 @CachePut 不同的返回类型
【发布时间】:2020-08-31 18:23:33
【问题描述】:

(Will Spring's @CachePut annotation work with a void return type?)

我遇到了同样的问题

因为问题很久了,不知道有没有解决办法

创建了一个缓存:

public static final String Key = "CacheKey";

@Cacheable(cacheNames = "userCache", key = "Key")
public List<User> getAllUsers() {
...
}

使用@CachePut 更新此缓存

@CachePut(cacheNames = "userCache", key = "Key")
public User addUser(User user) {
...
}

输出:

com.example.demo.dto.UserDTO cannot be cast to java.util.List

找了几天资料,没有找到答案

除了使用@CacheEvict (cacheNames = userCache, allEntries = true)

有没有办法使用@Cacheable 和@CachePut 来解决它?

谢谢

【问题讨论】:

    标签: java spring caching


    【解决方案1】:

    我建议阅读 Spring Cache Abstraction 的工作原理。 https://docs.spring.io/spring-framework/docs/5.0.0.BUILD-SNAPSHOT/spring-framework-reference/html/cache.html

    基本上,缓存本质上是键值存储。对于传递给方法的相同参数,检查缓存并返回缓存结果。如果该方法为 void,则没有要缓存的内容。 @CachePut 需要一个“值”来与“键”配对。如果要缓存添加的用户,addUser 需要返回一个用户。或者让 addUser 调用另一个方法并将 @CachePut 移动到该方法。

    您面临的另一个问题是,来自getAllUsersuserCacheList&lt;User&gt;,并且您打算(尽管由于无效而无法工作)将User 放入预期的同一缓存中List&lt;User&gt;

    换句话说,当你addUser时,你的userCache的List现在与getAllUsers的结果的实际状态不同步,所以你需要驱逐List的userCache

    p>

    改变 @CachePut(cacheNames = "userCache", key = "Key")

    @CacheEvict(cacheNames = "userCache", allEntries = true ) addUser 时,会清空 List 缓存,下次调用 getAllUsers 时,缓存会更新为当前的结果集。

    这篇文章几乎是 https://stackoverflow.com/a/59361298/3625077 的复制品,其中 Federico 提到这是一个常见的误解。缓存的值,不是可以操作的对象,即。在你的情况下,你不能 .add(user) 到userCache。它基本上是方法输入/输出的快照。

    【讨论】:

    • 你好,我实际上返回了User(内容已经修改),并且由于User和List ,我无法强制转换为java.util.List
    • 对,而不是 addUser 上的 @CachePut,将其更改为 @CacheEvict,,这会清除您的 List 缓存。下次调用 getAllUsers 时,会缓存现在更新的结果
    猜你喜欢
    • 2020-09-30
    • 2015-04-15
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多