温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用@CacheEvict 多参数怎么匹配删除

发布时间:2021-12-31 11:27:01 来源:亿速云 阅读:133 作者:小新 栏目:开发技术

这篇文章主要为大家展示了“使用@CacheEvict 多参数怎么匹配删除”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“使用@CacheEvict 多参数怎么匹配删除”这篇文章吧。

@CacheEvict 多参数匹配删除

如果@Cacheable(“XXX”)

Object getXXX(String a, String b, String c);

spring的缓存使用的key是ESPL表达式,然后翻看源码key默认用的生成方式是org.springframework.cache.interceptor.SimpleKeyGenerator

大于1个参数走的是最后一个方法

 /**
  * Generate a key based on the specified parameters.
  */
 public static Object generateKey(Object... params) {
  if (params.length == 0) {
   return SimpleKey.EMPTY;
  }
  if (params.length == 1) {
   Object param = params[0];
   if (param != null && !param.getClass().isArray()) {
    return param;
   }
  }
  return new SimpleKey(params);
 }

然后查看org.springframework.cache.interceptor.SimpleKey对应代码,发现返回的其实是SimpleKey

 /**
  * Create a new {@link SimpleKey} instance.
  * @param elements the elements of the key
  */
 public SimpleKey(Object... elements) {
  Assert.notNull(elements, "Elements must not be null");
  this.params = new Object[elements.length];
  System.arraycopy(elements, 0, this.params, 0, elements.length);
  this.hashCode = Arrays.deepHashCode(this.params);
 }

解决思路

方案一

单独写一个自定义的KeyGenerator,处理对应的key。(之前的redis的文章已写过,所以不重复写了)

下面博文的 MyKeyGenerator 这个类

sprintboot使用spring-security包,缓存内存与redis共存

方案二

@Cacheable(value=“XXX”, key=“xxxx”)
@CacheEvict(value=“XXX”, key=“xxxx”)

做相应的key配置

数组的话可以使用 key = “#root.args[0]”

参数参考如下:

名字位置描述示例
methodNameroot object当前被调用的方法名#root.methodName
methodroot object当前被调用的方法#root.method .name
targetroot object当前被调用的目标对象#root.target
targetClassroot object当前被调用的目标对象类#root.targetClass
argsroot object当前被调用的方法的参数列表#root.args[0]
cachesroot object当前方法调用使用的缓存列表#root.caches[0].name
argument nameevaluation context方法参数的名字,可以直接#参数名,也可以使用#p0或#a0的形式,0代表参数的索引#iban、#a0、#p0
resultevaluation context方法执行后的返回值#result

以上是“使用@CacheEvict 多参数怎么匹配删除”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI