经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring » 查看文章
Springboot Cache @CacheEvict 无法模糊删除的解决方案
来源:jb51  时间:2021/12/31 12:58:28  对本文有异议

SpringbootCache @CacheEvict 无法模糊删除

用@CacheEvict删除缓存只能删除指定key的缓存,有些情况需要根据前缀删除所有key的时候,用@CacheEvict就做不到了,所以我们自定义一个@CacheRemove来处理根据前缀模糊删除所有cache(支持Spring EL表达式)

以下代码适用于Redis

添加依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-aop</artifactId>
  4. </dependency>

启动类加上 @EnableAspectJAutoProxy

@CacheRemove 代码

  1. package com.marssvn.utils.annotation.cache;
  2. import java.lang.annotation.Retention;
  3. import java.lang.annotation.RetentionPolicy;
  4. import java.lang.annotation.Target;
  5. import static java.lang.annotation.ElementType.METHOD;
  6. @Target({METHOD})
  7. @Retention(RetentionPolicy.RUNTIME)
  8. public @interface CacheRemove {
  9. String[] value() default {};
  10. }

CacheRemoveAspect AOP实现类代码

  1. package com.marssvn.utils.annotation.cache.aspect;
  2. import com.marssvn.utils.annotation.cache.CacheRemove;
  3. import org.aspectj.lang.JoinPoint;
  4. import org.aspectj.lang.annotation.AfterReturning;
  5. import org.aspectj.lang.annotation.Aspect;
  6. import org.aspectj.lang.reflect.MethodSignature;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
  10. import org.springframework.data.redis.core.StringRedisTemplate;
  11. import org.springframework.expression.ExpressionParser;
  12. import org.springframework.expression.spel.standard.SpelExpressionParser;
  13. import org.springframework.expression.spel.support.StandardEvaluationContext;
  14. import org.springframework.stereotype.Component;
  15. import javax.annotation.Resource;
  16. import java.lang.reflect.Method;
  17. import java.util.Set;
  18. @Aspect
  19. @Component
  20. public class CacheRemoveAspect {
  21. @Resource
  22. private StringRedisTemplate stringRedisTemplate;
  23. private Logger logger = LoggerFactory.getLogger(this.getClass());
  24. @AfterReturning("@annotation(com.marssvn.utils.annotation.cache.CacheRemove)")
  25. public void remove(JoinPoint point) {
  26. Method method = ((MethodSignature) point.getSignature()).getMethod();
  27. CacheRemove cacheRemove = method.getAnnotation(CacheRemove.class);
  28. String[] keys = cacheRemove.value();
  29. for (String key : keys) {
  30. if (key.contains("#"))
  31. key = parseKey(key, method, point.getArgs());
  32. Set<String> deleteKeys = stringRedisTemplate.keys(key);
  33. stringRedisTemplate.delete(deleteKeys);
  34. logger.info("cache key: " + key + " deleted");
  35. }
  36. }
  37. /**
  38. * parseKey from SPEL
  39. */
  40. private String parseKey(String key, Method method, Object [] args){
  41. LocalVariableTableParameterNameDiscoverer u =
  42. new LocalVariableTableParameterNameDiscoverer();
  43. String[] paraNameArr = u.getParameterNames(method);
  44. ExpressionParser parser = new SpelExpressionParser();
  45. StandardEvaluationContext context = new StandardEvaluationContext();
  46. for (int i = 0; i < paraNameArr.length; i++) {
  47. context.setVariable(paraNameArr[i], args[i]);
  48. }
  49. return parser.parseExpression(key).getValue(context, String.class);
  50. }
  51. }

Service中的调用代码

  1. /**
  2. * Delete repository
  3. *
  4. * @param id repositoryId
  5. */
  6. @Override
  7. @Transactional
  8. @CacheRemove({"repository.list::*", "'repository::id=' + #id", "'repository.tree::id=' + #id + '*'"})
  9. public void deleteRepositoryById(int id) {
  10. // business code
  11. }

@CacheEvict根据缓存名称模糊删除

  1. @CacheEvict(cacheNames = "likename" ,allEntries=true)
  • allEntries=true 开启全匹配
  • cacheNames 填写 模糊删除的name

看源码可知

以上为个人经验,希望能给大家一个参考,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号