SpringCache整合redis時,使用嗡害,發(fā)現(xiàn)緩存并沒有刪除
@CacheEvict(value = "ParkConfig",allEntries = true)
查看源代碼CacheAspectSupport焚碌,這里調(diào)用的是doClear方法
查看doClear方法
這里調(diào)用了cache的clear方法,我們這里整合的REDIS霸妹,看一下redis的實現(xiàn)類
RedisCache.clear調(diào)用了cacheWriter的clean方法
打開DefaultRedisCacheWriter.clean 方法.DEBUG一下
debug發(fā)現(xiàn) pattern這個變量和redis客戶端里面的鍵不一致十电,命令也獲取不到任何數(shù)據(jù)
改成相應(yīng)的鍵可以
原因:由于redis被多個程序使用,所以我們在使用redis的時候給所有緩存都添加了一個前綴,而clear方法是直接使用的connect對象鹃骂,在使用鍵的時候沒有根據(jù)這個情況進(jìn)行序列化鍵台盯,
要解決這個問題也很簡單,DefaultRedisCacheWriter不允許繼承畏线,寫一個代理類静盅,修改clean方法
package cn.akeparking.middleware.cache.redis;
import org.springframework.data.redis.cache.RedisCacheWriter;
import java.time.Duration;
/**
* @Description
* @Author Mahz
* @Date2021/8/18 14:16
**/
public class MiddlewareRedisCacheWriterProxy implements RedisCacheWriter {
RedisCacheWriter redisCacheWriter;
MiddlewareKeySerializer middlewareKeySerializer;
public MiddlewareRedisCacheWriterProxy(RedisCacheWriter redisCacheWriter, MiddlewareKeySerializer middlewareKeySerializer) {
this.redisCacheWriter = redisCacheWriter;
this.middlewareKeySerializer = middlewareKeySerializer;
}
@Override
public void put(String name, byte[] key, byte[] value, Duration ttl) {
redisCacheWriter.put(name, key, value, ttl);
}
@Override
public byte[] get(String name, byte[] key) {
return redisCacheWriter.get(name, key);
}
@Override
public byte[] putIfAbsent(String name, byte[] key, byte[] value, Duration ttl) {
return redisCacheWriter.putIfAbsent(name, key, value, ttl);
}
@Override
public void remove(String name, byte[] key) {
redisCacheWriter.remove(name, key);
}
@Override
public void clean(String name, byte[] pattern) {
pattern = middlewareKeySerializer.serialize(new String(pattern));
redisCacheWriter.clean(name, pattern);
}
}
//初始化一個RedisCacheWriter
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
MiddlewareRedisCacheWriterProxy middlewareRedisCacheWriterProxy = new MiddlewareRedisCacheWriterProxy(redisCacheWriter,KeySerializer());
RedisTemplate redisTemplate = redisTemplate(connectionFactory);
RedisSerializationContext.SerializationPair<Object> value = RedisSerializationContext.SerializationPair
.fromSerializer(redisTemplate.getValueSerializer());
RedisSerializationContext.SerializationPair<String> key = RedisSerializationContext.SerializationPair
.fromSerializer(redisTemplate.getKeySerializer());
RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(value)
.serializeKeysWith(key);
defaultCacheConfig.entryTtl(Duration.ofDays(1));
return new RedisCacheManager(middlewareRedisCacheWriterProxy, defaultCacheConfig);
已經(jīng)能夠正常刪除