【问题标题】:Will Spring's @CachePut annotation work with a void return type?Spring 的 @CachePut 注释是否适用于 void 返回类型?
【发布时间】:2017-12-02 23:29:24
【问题描述】:

我正在尝试使用 Ehcache 和 Spring 3.1 内置的缓存注释(@Cacheable、@CacheEvict 和 @CachePut)在我的应用程序中实现缓存。

我已经创建了一个缓存如下:

@Cacheable(value = "userCache", key = "#user.id")
public List<User> getAllUsers() {
...
}

我正在尝试使用@CachePut 注释使用新值更新此缓存,如下所示:

@CachePut(value = "userCache", key = "#user.id")
public void addUser(User user) {
...
}

但是,新的“用户”并未添加到缓存中。这是因为返回类型为 void 的原因吗?

【问题讨论】:

    标签: spring caching annotations ehcache


    【解决方案1】:

    是的,这是因为 void 返回类型。 @CachePut 注释将方法的结果放入缓存中。在您的情况下,没有结果,因此没有任何内容放入缓存。

    更改方法签名以返回用户:

    public User addUser(User user) { 
       ...
    }
    

    【讨论】:

      【解决方案2】:

      这不起作用,因为您使用的是相同的缓存值“userCache”,但 getAllUsers 方法的返回类型是 List,addUser 的返回类型是 User。这将导致存储在缓存中的数据不一致。

      (List + User):这种类型的数据会在缓存中形成。

      稍后当您调用方法 getAllUsers 时,代码将是

      列出用户列表 = getAllUsers();

      但在这种情况下,数据将从缓存中获取并抛出“Class cast Exception”。

      As , ( List + User ) 不能转换成 List。

      有什么解决办法吗?我坚持这一点,不知道如何继续。在这里可以使用自定义注释吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-21
        • 2016-08-16
        • 1970-01-01
        • 2020-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-12
        相关资源
        最近更新 更多