使用@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 多参数如何匹配删除 的全部内容, 来源链接: utcz.com/p/252005.html

回到顶部