How to use @CachePut and @CacheEvict on the same method in a Spring Boot application?

情到浓时终转凉″ 提交于 2021-02-08 08:56:30

问题


I'm working on a Spring Boot application where I have a scenario to put @CachePut and @CacheEvict on the same method.

I tried the scenario with this code given below :

@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);
}

But this doesn't seem to work as expected.

Objectives :

  • I want @CachePut annotation to always execute first since that will be the first validation to update the cache.

  • @CacheEvict is executed whenever the condition is satisfied (i.e. isDeleted field is set to true)

  • I don't want my cache to be updated or add a new entry if isDeleted is set to true.

Is it possible to achieve this in Spring ? How should I modify my code ?


回答1:


You can achieve the use of multiple different cache annotations on the same method in Spring using @Caching annotation.

Note: This works when different caches are used.

According to Spring Cache Abstraction Docs:

When multiple annotations such as @CacheEvict or @CachePut is needed to be specified on the same method for different caches.

Then to achieve this, the workaround is to use @Caching. @Caching allows multiple nested @Cacheable, @CachePut and @CacheEvict to be used on the same method.

Try this (if it works) :

@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 for reference.



来源:https://stackoverflow.com/questions/62483596/how-to-use-cacheput-and-cacheevict-on-the-same-method-in-a-spring-boot-applica

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!