开发者

使用redisTemplate的scan方式删除批量key问题

开发者 https://www.devze.com 2023-12-21 10:26 出处:网络 作者: bat在等我
目录RedisTemplate的scan方式删除批量keyJava使用RedisTemplate模糊删除key总结redisTemplate的scan方式删除批量key
目录
  • RedisTemplate的scan方式删除批量key
  • Java使用RedisTemplate模糊删除key
  • 总结

redisTemplate的scan方式删除批量key

	/**
     * 删除指定前缀的一系列key
     *
     * @param pattern 匹配keys的规则
     */
    public void deleteKeysByScan(String pattern) {
        long start = System.currentTimeMillis();
        LOGGER.error("清理{}类外呼记录缓存的定时任务开始执行", pattern);
        String param = pattern + "*";
        Set<String> keys = this.getValuesForStringByScan(param);
        redisTemplate.delete(keys);
        LOGGER.error("清理{}类外呼记录缓存的定时任务执行结束,耗时:{}", pattern, (System.currentTimeMillis() - start));
    }

    /**
     * 获取匹配的所有key,使用scan避免阻塞
     *
     * @param patten 匹配keys的规则
     * @return 返回获取到的keys
     */
    public Set<String> getValuesForStringByScan(String patten) {
        return redisTemplate.execute(connect -> {
            Set<String> binaryKeys = new HashSet<>();
            Cursor<byte[]> cursor = connect.scan(new ScanOjavascriptptions.ScanOptionsBuilder().match(patten).count(200000).build());
            while (cursor.hasNext() && binaryKeys.size() < 200000) {
                binaryKeys.add(new String(cursor.next()));
            }
       php     return binaryKeys;
        }, true);
    }

Java使用RedisTemplate模糊删除key

Redis模糊匹配批量删除操作,使用RedisTKPILamemplate操作:

    public void deleteByPrex(String prex) {
        Set<String> keys = redisTemplate.keys(prex);
        if (CollectionUtils.isNotEmpty(keKPILamys)) {
            redisTemplate.delete(keys);
        }
    }

prex为迷糊匹配的key,如cache:user:*

这里需要判断keys是否存在,如果一个都匹配不到会报错:

ERR wrong number of arguments for 'del' command

当然编程客栈,如果要直接在linux里面操作的话,在命令行执行以下命令:

redis-cli keys "keys" | xargs redis-cli del

keys 是要匹配的规则,和上面的prex一样。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号