[英]Spring Cache - @CacheEvict, @CachePut not working while calling from the another method from the same class
[英]How to use @CachePut and @CacheEvict on the same method in a Spring Boot application?
我正在开发一个 Spring 引导应用程序,我有一个场景可以将@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
注释始终首先执行,因为这将是更新缓存的第一个验证。
只要满足条件(即isDeleted
字段设置为true
),就会执行@CacheEvict
如果isDeleted
设置为true
,我不希望更新我的缓存或添加新条目。
是否有可能在 Spring 中实现这一点? 我应该如何修改我的代码?
您可以使用@Caching
注解在Spring中的同一方法上实现多个不同缓存注解的使用。
注意:这在使用不同的缓存时有效。
当需要为不同的缓存在同一个方法上指定多个注解(如
@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 文档供参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.