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

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

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

(0)

相关推荐

  • ehcache模糊批量移除缓存的方法

    前言 众所周知,encache是现在最流行的java开源缓存框架,配置简单,结构清晰,功能强大.通过注解 @Cacheable 可以快速添加方法结果到缓存.通过 @CacheEvict 可以快速清除掉指定的缓存. 但由于 @CacheEvict 注解使用的是key-value的,不支持模糊删除,就会遇到问题.当我用 @Cacheable 配合Spring EL表达式添加了同一方法的多个缓存比如: @GetMapping("/listOfTask/{page}/") @Cacheable

  • @CacheEvict 清除多个key的实现方式

    借用@Caching实现 入参是基本类型的: @Caching(evict={@CacheEvict(value = Cache.CONSTANT, key = "'" + CacheKey.SINGLE_ROLE_NAME + "'+#roleId"), @CacheEvict(value = Cache.CONSTANT, key = "'" + CacheKey.ROLES_NAME + "'+#roleId"), @C

  • Spring Cache手动清理Redis缓存

    这篇文章主要介绍了Spring Cache手动清理Redis缓存,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 注册cacheRedisTemplate 将 cache 的 RedisTemplate 注册为Bean @Bean(name = "cacheRedisTemplate") public RedisTemplate cacheRedisTemplate(@Qualifier("jedisConnectionFac

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

    目录 @CacheEvict + redis批量删除缓存 一.@Cacheable注解 二.@CacheEvict注解 三.批量删除缓存 四.代码 @CacheEvict清除指定下所有缓存 @CacheEvict + redis批量删除缓存 一.@Cacheable注解 添加缓存. /** * @Cacheable * 将方法的运行结果进行缓存:以后再要相同的数据,直接从缓存中获取,不用调用方法: * CacheManager管理多个Cache组件,对缓存的真正CRUD操作在Cache组件中,每

  • 使用Redis缓存时高效的批量删除的几种方案

    目录 前因后果 批量删除redis数据方法 利用的是Linux的xargs命令 xargs指令 命令格式 参数: 使用Lua脚本删除百万/千万级的key Lua脚本是什么? Lua脚本的指令格式 Lua脚本执行参数 Lua获取传参数据 示例 Lua脚本的案例(keys) scan介绍 Lua脚本的案例(scan) 前因后果 之前我们的服务,在上线的时候发现有一些大Key的使用不是很规范,特别是没有设置过期时间,因此导致redis中内存的数据越来越多,目前Redis节点的内存已经快撑不住了.所以根

  • Redis批量删除KEY的方法

    Redis 中有删除单个 Key 的指令 DEL,但好像没有批量删除 Key 的指令,不过我们可以借助 Linux 的 xargs 指令来完成这个动作. 复制代码 代码如下: redis-cli keys "*" | xargs redis-cli del //如果redis-cli没有设置成系统变量,需要指定redis-cli的完整路径 //如:/opt/redis/redis-cli keys "*" | xargs /opt/redis/redis-cli d

  • python中redis查看剩余过期时间及用正则通配符批量删除key的方法

    具体代码如下所示: # -*- coding: utf-8 -*- import redis import datetime ''' # 1. redis设置过期时间的两种方式 expire函数设置过期时间为10秒.10秒后,ex1将会失效 expireat设置一个具体的时间,15年9月8日15点19分10秒,过了这个时间,ex2将失效 如果设置过期时间成功会返回True,反之返回False ''' pool = redis.ConnectionPool(host='192.168.3.128'

  • redis批量删除key的步骤

    由于误用插件,某台服务器上的redis实例存在数百万无用的key.为了删除无用数据,上网查找redis批量删除key的方法,发现使用过程中都有问题.经过本人的研究,终于找到redis批量删除key的正确用法. 本文分享最新版Redis批量删除key的方法,希望能帮到遇到同样问题的网友. redis批量删除key 网上许多文章和教程给出的redis批量删除key命令是: redis-cli KEYS "$PATTERN" | xargs redis-cli DEL 在本人的实践中,这条命

  • Redis使用元素删除的布隆过滤器来解决缓存穿透问题

    目录 前言 缓存雪崩 解决方案 缓存击穿 解决方案 缓存穿透 解决方案 布隆过滤器(Bloom Filter) 什么是布隆过滤器 位图(Bitmap) 哈希碰撞 布隆过滤器的2大特点 fpp 布隆过滤器的实现(Guava) 布隆过滤器的如何删除 带有计数器的布隆过滤器 总结 前言 在我们日常开发中,Redis使用场景最多的就是作为缓存和分布式锁等功能来使用,而其用作缓存最大的目的就是为了降低数据库访问.但是假如我们某些数据并不存在于Redis当中,那么请求还是会直接到达数据库,而一旦在同一时间大

  • 解决redis批量删除key值的问题

    遇到的问题: 在开发过程中,会遇到要批量删除某种规则的key,例如login_logID(ID为变量),现在需要删除"login_log*"这一类的数据,但是redis本身只有批量查询一类key值的命令keys,但是没有批量删除某一个类的命令. 解决办法: 先查询,在删除,使用xargs传参(xargs可以将管道或标准输入(stdin)数据转换成命令行参数),先执行查询语句,在将查询出来的key值,当初del的参数去删除. redis-cli KEYS key* (查找条件) | xa

  • 分布式医疗挂号系统SpringCache与Redis为数据字典添加缓存

    目录 一.SpringCache介绍 二.项目集成Spring Cache 1.添加缓存相关依赖 2.添加redis配置类 3.添加redos配置 三.数据字典配置Spring Cache 1.缓存@Cacheable 2.缓存@CachePut 四.测试缓存是否添加成功 一.SpringCache介绍 Spring Cache 是一个优秀的缓存组件.自Spring 3.1起,提供了类似于@Transactional注解事务的注解Cache支持,且提供了Cache抽象,方便切换各种底层Cache

  • Redis三种常用的缓存读写策略步骤详解

    目录 一.Redis三种常用的缓存读写策略 二.旁路缓存模式(Cache Aside Pattern) 读写步骤 写: 读: 自我思考 缺点 三.读写穿透(Read/Write Through Pattern) 读写步骤 写: 读: 四.异步缓存写入(Write Behind Pattern) 一.Redis三种常用的缓存读写策略 Redis有三种读写策略分别是:旁路缓存模式策略.读写穿透策略.异步缓存写入策略. 这三种缓存读写策略各有优势,不存在最佳,需要我们根据实际的业务场景选择最合适的.

  • Redis+Caffeine两级缓存的实现

    目录 优点与问题 准备工作 V1.0版本 V2.0版本 V3.0版本 在高性能的服务架构设计中,缓存是一个不可或缺的环节.在实际的项目中,我们通常会将一些热点数据存储到Redis或MemCache这类缓存中间件中,只有当缓存的访问没有命中时再查询数据库.在提升访问速度的同时,也能降低数据库的压力. 随着不断的发展,这一架构也产生了改进,在一些场景下可能单纯使用Redis类的远程缓存已经不够了,还需要进一步配合本地缓存使用,例如Guava cache或Caffeine,从而再次提升程序的响应速度与

随机推荐