redis模糊查找key spring redis 怎样实现模糊查找key

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

redis模糊查找key spring redis 怎样实现模糊查找key

路过君_P   2021-08-10 我要评论
想了解spring redis 怎样实现模糊查找key的相关内容吗,路过君_P在本文为您仔细讲解redis模糊查找key的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:spring,redis,模糊查找key,redis模糊查找,下面大家一起来学习吧。

spring redis 模糊查找key

用法

Set<String> keySet = stringRedisTemplate.keys("keyprefix:"+"*");
  • 需要使用StringRedisTemplate,或自定义keySerializer为StringRedisSerializer的redisTemplate
  • redis里模糊查询key允许使用的通配符:

     * 任意多个字符

     ? 单个字符

     [] 括号内的某1个字符

源码

org.springframework.data.redis.core.RedisTemplate
public Set<K> keys(K pattern) {
 byte[] rawKey = rawKey(pattern);
 Set<byte[]> rawKeys = execute(connection -> connection.keys(rawKey), true);
 return keySerializer != null ? SerializationUtils.deserialize(rawKeys, keySerializer) : (Set<K>) rawKeys;
}

改善

  • Redis2.8以后可以使用scan获取key
  • 基于游标迭代分次遍历key,不会一次性扫描所有key导致性能消耗过大,减少服务器阻塞

可以通过count参数设置扫描的范围

Set<String> keys = new LinkedHashSet<>();
stringRedisTemplate.execute((RedisConnection connection) -> {
    try (Cursor<byte[]> cursor = connection.scan(
            ScanOptions.scanOptions()
                    .count(Long.MAX_VALUE)
                    .match(pattern)
                    .build()
    )) {
        cursor.forEachRemaining(item -> {
            keys.add(RedisSerializer.string().deserialize(item));
        });
        return null;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
});

Reids SCAN命令官方文档

redis-redisTemplate模糊匹配删除

 String key = "noteUserListenedPoi:*";
            redisTemplate.delete(key);
            LOGGER.info("redis中用户收听历史被清空");

后来测试发现模糊查询是可以用的, 删除改成

Set<String> keys = redisTemplate.keys("noteUserListenedPoi:" + "*");
            redisTemplate.delete(keys);
            LOGGER.info("{}, redis中用户收听历史被清空"

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们