【问题标题】:Calling @CacheEvict and @Cacheable annotation on a single method?在单个方法上调用 @CacheEvict 和 @Cacheable 注释?
【发布时间】:2016-04-26 09:32:06
【问题描述】:

我正在尝试在单个方法上调用 @CacheEvict 和 @Cacheable 注释。

@CacheEvict(value = "tripDetailsDashboardCache", key = "#userId")
@Cacheable(value ="tripDetailsDashboardCache", key="#userId")
public  List<DashBoardObject> getAllDetailsForDashBoard(Integer userId){
    List<Master> masters = tripDetailsService.getTripDetailsForCaching(userId);
    List<DashBoardObject> dashBoardObject = tripDetailsService.getMasterDetailsForDashBoard(userId, masters);
    return dashBoardObject;
}

在调用@CacheEvict 时,我想删除特定键的缓存数据,并再次缓存方法响应的新数据。但它没有缓存新数据?而且它没有给出任何错误?。

【问题讨论】:

    标签: spring-cache spring-data-redis


    【解决方案1】:

    我想你想更新缓存,所以尝试使用@CachePut,方法在所有情况下都会执行,如果key是新的,新的记录会被添加到缓存中,如果记录是旧的,旧的值将被新值更新(刷新值)。

    @CachePut(value = "tripDetailsDashboardCache", key = "#userId")
    public  List<DashBoardObject> getAllDetailsForDashBoard(Integer userId){
        List<Master> masters = tripDetailsService.getTripDetailsForCaching(userId);
        List<DashBoardObject> dashBoardObject = tripDetailsService.getMasterDetailsForDashBoard(userId, masters);
        return dashBoardObject;
    }
    

    【讨论】:

      【解决方案2】:

      @CacheEvict 默认在方法调用之后运行。所以上面的方法用#userId键缓存列表,然后彻底清除缓存。

      它使代码不清楚我建议创建单独的可缓存和缓存驱逐方法

      【讨论】:

      • 我创建了单独的可缓存和缓存驱逐方法。但它没有按我的要求工作。要求是我将预订一张票,它将存储在数据库中,之后我将调用这两个缓存方法,然后我将单击仪表板按钮,此时它应该从缓存中获取数据,但它没有获取。并且没有错误。
      • 我想在同一个方法上同时调用 CacheEvict 和 Cacheable。因为首先我想从缓存中删除数据,然后我想加载新数据。是否可以在同一个方法上调用两个注释。
      • "beforeInvocation = true" 设置可以使用。但很难预测谁会赢:CacheEvict 或 Cacheable
      【解决方案3】:

      看看docs。有@Caching 注解,您可以在其中定义@Cacheable、@CachePut 和@CacheEvict

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-02
        • 2018-05-06
        • 2013-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多