问题
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
@CachePutannotation to always execute first since that will be the first validation to update the cache.@CacheEvictis executed whenever the condition is satisfied (i.e.isDeletedfield is set totrue)I don't want my cache to be updated or add a new entry if
isDeletedis set totrue.
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
@CacheEvictor@CachePutis needed to be specified on the same method for different caches.
Then to achieve this, the workaround is to use
@Caching.@Cachingallows multiple nested@Cacheable,@CachePutand@CacheEvictto 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