广告
返回顶部
首页 > 资讯 > 后端开发 > Python >@CacheEvict + redis实现批量删除缓存
  • 882
分享到

@CacheEvict + redis实现批量删除缓存

2024-04-02 19:04:59 882人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

目录@CacheEvict + Redis批量删除缓存一、@Cacheable注解二、@CacheEvict注解三、批量删除缓存四、代码@CacheEvict清除指定下所有缓存@Ca

@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一下清除所有的元素。

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

--结束END--

本文标题: @CacheEvict + redis实现批量删除缓存

本文链接: https://www.lsjlt.com/news/137883.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作