@CacheEvict + redis实现批量删除缓存
@CacheEvict + redis批量删除缓存
一、@Cacheable注解
添加缓存。
二、@CacheEvict注解
清除缓存。
cacheNames/value: | 指定缓存组件的名字;将方法的返回结果放在哪个缓存中,是数组的方式,可以指定多个缓存; |
key | 缓存数据使用的key |
allEntries | 是否清除这个缓存中所有的数据。true:是;false:不是 |
beforeInvocation | 缓存的清除是否在方法之前执行,默认代表缓存清除操作是在方法执行之后执行;如果出现异常缓存就不会清除。true:是;false:不是 |
三、批量删除缓存
现实应用中,某些缓存都有相同的前缀或者后缀,数据库更新时,需要删除某一类型(也就是相同前缀)的缓存。
而@CacheEvict只能单个删除key,不支持模糊匹配删除。
解决办法:使用redis + @CacheEvict解决。
@CacheEvict实际上是调用RedisCache的evict方法删除缓存的。下面为RedisCache的部分代码,可以看到,evict方法是不支持模糊匹配的,而clear方法是支持模糊匹配的。
@Override
public void evict(Object key) {
cacheWriter.remove(name, createAndConvertCacheKey(key));
}
@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);
}
public void evictLikePrefix(String key) {
byte[] pattern = this.conversionService.convert(this.createCacheKey(key), byte[].class);
this.cacheWriter.clean(this.name, pattern);
}
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);
}
@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一下清除所有的元素。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341