【问题标题】:How to use @CachePut and @CacheEvict on the same method in a Spring Boot application?如何在 Spring Boot 应用程序中的同一方法上使用 @CachePut 和 @CacheEvict?
【发布时间】:2020-06-20 08:43:08
【问题描述】:

我正在开发一个 Spring Boot 应用程序,我有一个场景可以将 @CachePut@CacheEvict 放在同一个方法上。

我用下面给出的代码尝试了这个场景:

@CachePut(value="myValue",key="#entity.getId(),#entity.getOrgId()", 
          cacheManager="no-expire-caching")
@CacheEvict(value="myValue", key="#entity.getId(),#entity.getOrgId()",
          cacheManager="no-expire-caching", condition="#entity.isDeleted() == true")
public MyEntity save(boolean flag, MyEntity entity){
    if (flag==true){
        entity.setIsDeleted(true);
        return myRepo.save(entity);
    }
    return myRepo.save(entity);
}

但这似乎没有按预期工作。

目标:

  • 我希望@CachePut 注释始终首先执行,因为这将是更新缓存的第一个验证。

  • 只要满足条件,就会执行@CacheEvict(即isDeleted字段设置为true

  • 如果isDeleted 设置为true,我不希望更新我的缓存或添加新条目。

是否有可能在 Spring 中实现这一点?我应该如何修改我的代码?

【问题讨论】:

  • CachePut 也可以使用条件。

标签: java spring spring-boot spring-cache


【解决方案1】:

在Spring中使用@Caching注解可以实现在同一个方法上使用多个不同的缓存注解。

注意:这在使用不同的缓存时有效。

根据Spring Cache Abstraction Docs

当多个注解如@CacheEvict@CachePut对于不同的缓存需要在同一个方法上指定。

那么要实现这一点,解决方法是使用@Caching@Caching 允许多个嵌套的@Cacheable@CachePut@CacheEvict 用于相同的方法。

试试这个(如果可行的话):

@Caching(put={@CachePut(value="myValue",key="#entity.getId(),#entity.getOrgId()", 
          cacheManager="no-expire-caching")}, evict = {@CacheEvict(value="myValue", key="#entity.getId(),#entity.getOrgId()",
          cacheManager="no-expire-caching", condition="#entity.isDeleted() == true")})
public MyEntity save(boolean flag, MyEntity entity){
    if (flag==true){
        entity.setIsDeleted(true);
        return myRepo.save(entity);
    }
    return myRepo.save(entity);
}

@Caching Java Docs供参考。

【讨论】:

    猜你喜欢
    • 2021-01-28
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 2018-02-02
    • 2015-12-28
    • 2021-02-25
    • 2019-09-05
    相关资源
    最近更新 更多