欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用@CacheEvict 多参数如何匹配删除

程序员文章站 2022-06-24 18:34:29
目录@cacheevict 多参数匹配删除解决思路方案一方案二@cacheevict 多参数匹配删除如果@cacheable(“xxx”)object getxxx(string a, string...

@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 这个类

方案二

@cacheable(value=“xxx”, key=“xxxx”)
@cacheevict(value=“xxx”, key=“xxxx”)

做相应的key配置

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

参数参考如下:

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

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