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命令官方文档

posted on   路过君  阅读(2022)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
历史上的今天:
2020-04-11 spring 启动时自动运行
2020-04-11 spring cloud oauth2授权服务 默认tokenService配置源码
2020-04-11 spring cloud 搭建oauth2授权服务 使用redis存储令牌
2020-04-11 spring cloud oauth2授权服务 clientDetails配置源码
2020-04-11 spring 验证框架
2020-04-11 IDEA 插件整理
2020-04-11 spring security笔记 默认登陆页面源码

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示