目录
- @cacheevict + redis批量删除缓存
- 一、@cacheable注解
- 二、@cacheevict注解
- @cacheevict清除指定下所有缓存
@cacheevict + redis批量删除缓存
一、@cacheable注解
添加缓存。
/**
* @cacheable
* 将方法的运行结果进行缓存;以后再要相同的数据,直接从缓存中获取,不用调用方法;
* cachemanager管理多个cache组件,对缓存的真正crud操作在cache组件中,每一个缓存组件有自己唯一一个名字;
*
*
* 原理:
* 1、自动配置类;cacheautoconfiguration
* 2、缓存的配置类
* org.springframework.boot.autoconfigure.cache.genericcacheconfiguration
* org.springframework.boot.autoconfigure.cache.jcachecacheconfiguration
* org.springframework.boot.autoconfigure.cache.ehcachecacheconfiguration
* org.springframework.boot.autoconfigure.cache.hazelcastcacheconfiguration
* org.springframework.boot.autoconfigure.cache.infinispancacheconfiguration
* org.springframework.boot.autoconfigure.cache.couchbasecacheconfiguration
* org.springframework.boot.autoconfigure.cache.rediscacheconfiguration
* org.springframework.boot.autoconfigure.cache.caffeinecacheconfiguration
* org.springframework.boot.autoconfigure.cache.guavacacheconfiguration
* org.springframework.boot.autoconfigure.cache.simplecacheconfiguration【默认】
* org.springframework.boot.autoconfigure.cache.noopcacheconfiguration
* 3、哪个配置类默认生效:simplecacheconfiguration;
*
* 4、给容器中注册了一个cachemanager:concurrentmapcachemanager
* 5、可以获取和创建concurrentmapcache类型的缓存组件;他的作用将数据保存在concurrentmap中;
*
* 运行流程:
* @cacheable:
* 1、方法运行之前,先去查询cache(缓存组件),按照cachenames指定的名字获取;
* (cachemanager先获取相应的缓存),第一次获取缓存如果没有cache组件会自动创建。
* 2、去cache中查找缓存的内容,使用一个key,默认就是方法的参数;
* key是按照某种策略生成的;默认是使用keygenerator生成的,默认使用simplekeygenerator生成key;
* simplekeygenerator生成key的默认策略;
* 如果没有参数;key=new simplekey();
* 如果有一个参数:key=参数的值
* 如果有多个参数:key=new simplekey(params);
* 3、没有查到缓存就调用目标方法;
* 4、将目标方法返回的结果,放进缓存中
*
* @cacheable标注的方法执行之前先来检查缓存中有没有这个数据,默认按照参数的值作为key去查询缓存,
* 如果没有就运行方法并将结果放入缓存;以后再来调用就可以直接使用缓存中的数据;
*
* 核心:
* 1)、使用cachemanager【concurrentmapcachemanager】按照名字得到cache【concurrentmapcache】组件
* 2)、key使用keygenerator生成的,默认是simplekeygenerator
*
*
* 几个属性:
* cachenames/value:指定缓存组件的名字;将方法的返回结果放在哪个缓存中,是数组的方式,可以指定多个缓存;
*
* key:缓存数据使用的key;可以用它来指定。默认是使用方法参数的值 1-方法的返回值
* 编写spel; #i d;参数id的值 #a0 #p0 #root.args[0]
* getemp[2]
*
* keygenerator:key的生成器;可以自己指定key的生成器的组件id
* key/keygenerator:二选一使用;
*
*
* cachemanager:指定缓存管理器;或者cacheresolver指定获取解析器
*
* condition:指定符合条件的情况下才缓存;
* ,condition = "#id>0"
* condition = "#a0>1":第一个参数的值》1的时候才进行缓存
*
* unless:否定缓存;当unless指定的条件为true,方法的返回值就不会被缓存;可以获取到结果进行判断
* unless = "#result == null"
* unless = "#a0==2":如果第一个参数的值是2,结果不缓存;
* sync:是否使用异步模式
*
*/
二、@cacheevict注解
清除缓存。
| cachenames/value: | 指定缓存组件的名字;将方法的返回结果放在哪个缓存中,是数组的方式,可以指定多个缓存; |
| key | 缓存数据使用的key |
| allentries | 是否清除这个缓存中所有的数据。true:是;false:不是 |
| beforeinvocation | 缓存的清除是否在方法之前执行,默认代表缓存清除操作是在方法执行之后执行;如果出现异常缓存就不会清除。true:是;false:不是 |
三、批量删除缓存
现实应用中,某些缓存都有相同的前缀或者后缀,数据库更新时,需要删除某一类型(也就是相同前缀)的缓存。
而@cacheevict只能单个删除key,不支持模糊匹配删除。
解决办法:使用redis + @cacheevict解决。
@cacheevict实际上是调用rediscache的evict方法删除缓存的。下面为rediscache的部分代码,可以看到,evict方法是不支持模糊匹配的,而clear方法是支持模糊匹配的。
/*
* (non-javadoc)
* @see org.springframework.cache.cache#evict(java.lang.object)
*/
@override
public void evict(object key) {
cachewriter.remove(name, createandconvertcachekey(key));
}
/*
* (non-javadoc)
* @see org.springframework.cache.cache#clear()
*/
@override
public void clear() {
byte[] pattern = conversionservice.convert(createcachekey("*"), byte[].class);
cachewriter.clean(name, pattern);
}
所以,只需重写rediscache的evict方法就可以解决模糊匹配删除的问题。
四、代码
4.1 自定义rediscache:
public class customizedrediscache extends rediscache {
private static final string wild_card = "*";
private final string name;
private final rediscachewriter cachewriter;
private final conversionservice conversionservice;
protected customizedrediscache(string name, rediscachewriter cachewriter, rediscacheconfiguration cacheconfig) {
super(name, cachewriter, cacheconfig);
this.name = name;
this.cachewriter = cachewriter;
this.conversionservice = cacheconfig.getconversionservice();
}
@override
public void evict(object key) {
if (key instanceof string) {
string keystring = key.tostring();
if (keystring.endswith(wild_card)) {
evictlikesuffix(keystring);
return;
}
if (keystring.startswith(wild_card)) {
evictlikeprefix(keystring);
return;
}
}
super.evict(key);
}
/**
* 前缀匹配
*
* @param key
*/
public void evictlikeprefix(string key) {
byte[] pattern = this.conversionservice.convert(this.createcachekey(key), byte[].class);
this.cachewriter.clean(this.name, pattern);
}
/**
* 后缀匹配
*
* @param key
*/
public void evictlikesuffix(string key) {
byte[] pattern = this.conversionservice.convert(this.createcachekey(key), byte[].class);
this.cachewriter.clean(this.name, pattern);
}
}
4.2 重写rediscachemanager,使用自定义的rediscache:
public class customizedrediscachemanager extends rediscachemanager {
private final rediscachewriter cachewriter;
private final rediscacheconfiguration defaultcacheconfig;
private final map<string, rediscacheconfiguration> initialcaches = new linkedhashmap<>();
private boolean enabletransactions;
public customizedrediscachemanager(rediscachewriter cachewriter, rediscacheconfiguration defaultcacheconfiguration) {
super(cachewriter, defaultcacheconfiguration);
this.cachewriter = cachewriter;
this.defaultcacheconfig = defaultcacheconfiguration;
}
public customizedrediscachemanager(rediscachewriter cachewriter, rediscacheconfiguration defaultcacheconfiguration, string... initialcachenames) {
super(cachewriter, defaultcacheconfiguration, initialcachenames);
this.cachewriter = cachewriter;
this.defaultcacheconfig = defaultcacheconfiguration;
}
public customizedrediscachemanager(rediscachewriter cachewriter, rediscacheconfiguration defaultcacheconfiguration, boolean allowinflightcachecreation, string... initialcachenames) {
super(cachewriter, defaultcacheconfiguration, allowinflightcachecreation, initialcachenames);
this.cachewriter = cachewriter;
this.defaultcacheconfig = defaultcacheconfiguration;
}
public customizedrediscachemanager(rediscachewriter cachewriter, rediscacheconfiguration defaultcacheconfiguration, map<string, rediscacheconfiguration> initialcacheconfigurations) {
super(cachewriter, defaultcacheconfiguration, initialcacheconfigurations);
this.cachewriter = cachewriter;
this.defaultcacheconfig = defaultcacheconfiguration;
}
public customizedrediscachemanager(rediscachewriter cachewriter, rediscacheconfiguration defaultcacheconfiguration, map<string, rediscacheconfiguration> initialcacheconfigurations, boolean allowinflightcachecreation) {
super(cachewriter, defaultcacheconfiguration, initialcacheconfigurations, allowinflightcachecreation);
this.cachewriter = cachewriter;
this.defaultcacheconfig = defaultcacheconfiguration;
}
/**
* 这个构造方法最重要
**/
public customizedrediscachemanager(redisconnectionfactory redisconnectionfactory, rediscacheconfiguration cacheconfiguration) {
this(rediscachewriter.nonlockingrediscachewriter(redisconnectionfactory),cacheconfiguration);
}
/**
* 覆盖父类创建rediscache
*/
@override
protected rediscache createrediscache(string name, @nullable rediscacheconfiguration cacheconfig) {
return new customizedrediscache(name, cachewriter, cacheconfig != null ? cacheconfig : defaultcacheconfig);
}
@override
public map<string, rediscacheconfiguration> getcacheconfigurations() {
map<string, rediscacheconfiguration> configurationmap = new hashmap<>(getcachenames().size());
getcachenames().foreach(it -> {
rediscache cache = customizedrediscache.class.cast(lookupcache(it));
configurationmap.put(it, cache != null ? cache.getcacheconfiguration() : null);
});
return collections.unmodifiablemap(configurationmap);
}
}
4.3 在redistemplateconfig中使用自定义的cachemanager
@bean
public cachemanager onedaycachemanager(redisconnectionfactory factory) {
redisserializer<string> redisserializer = new stringredisserializer();
jackson2jsonredisserializer jackson2jsonredisserializer = new jackson2jsonredisserializer(object.class);
//解决查询缓存转换异常的问题
objectmapper om = new objectmapper();
om.setvisibility(propertyaccessor.all, jsonautodetect.visibility.any);
om.enabledefaulttyping(objectmapper.defaulttyping.non_final);
jackson2jsonredisserializer.setobjectmapper(om);
// 配置序列化(解决乱码的问题)
rediscacheconfiguration config = rediscacheconfiguration.defaultcacheconfig()
// 1天缓存过期
.entryttl(duration.ofdays(1))
.serializekeyswith(redisserializationcontext.serializationpair.fromserializer(redisserializer))
.serializevalueswith(redisserializationcontext.serializationpair.fromserializer(jackson2jsonredisserializer))
.computeprefixwith(name -> name + ":")
.disablecachingnullvalues();
return new customizedrediscachemanager(factory, config);
}
4.4 在代码方法上使用@cacheevict模糊匹配删除
@cacheable(value = "current_group", cachemanager = "onedaycachemanager",
key = "#currentattendancegroup.getid() + ':' + args[1]", unless = "#result eq null")
public string getcacheattendanceid(currentattendancegroupdo currentattendancegroup, string datestr) {
// 方法体
}
@cacheevict(value = "current_group", key = "#currentattendancegroup.getid() + ':' + '*'", beforeinvocation = true)
public void deletecacheattendanceid(currentattendancegroupdo currentattendancegroup) {
}
注意:如果redistemplateconfig中有多个cachemanager,可以使用@primary注解标注默认生效的cachemanager
@cacheevict清除指定下所有缓存
@cacheevict(cachenames = "parts:grid",allentries = true)
此注解会清除part:grid下所有缓存
@cacheevict要求指定一个或多个缓存,使之都受影响。
此外,还提供了一个额外的参数allentries 。表示是否需要清除缓存中的所有元素。
默认为false,表示不需要。当指定了allentries为true时,spring cache将忽略指定的key。
有的时候我们需要cache一下清除所有的元素。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。