Java Redis获取key的方式

方案一:keys *

keys的模糊匹配功能很方便也很强大,但是在生产环境需要慎用!

开发中使用keys的模糊匹配却发现redis的CPU使用率极高,所以公司的redis生产环境将keys命令禁用了!redis是单线程,会被堵塞

方案二:scan

SCAN 命令是一个基于游标的迭代器,SCAN命令每次被调用之后,都会向用户返回一个新的游标,用户在下次选代时需要使用这个新游标作为SCAN命令的游标参数,以此来延续之前的选代过程。

代码实现

scan方法

typescript 复制代码
/**
 * 扫描主键,建议使用
 * @param patten
 * @return
 */
public Set<String> scan(String patten){
    Set<String> keys = stringRedisTemplate.execute((RedisCallback<Set<String>>) connection -> {
        Set<String> result = new HashSet<>();
        try (Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder()
                .match(patten).count(10000).build())) {
            while (cursor.hasNext()) {
                result.add(new String(cursor.next()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    });
    return  keys;
}

使用

匹配"future_*"开头的所有key

typescript 复制代码
@Test
public void keys(){
    Set<String> scan = cacheService.scan("future_*");
    System.out.println(scan);
}
相关推荐
uzong10 小时前
程序员从大厂回重庆工作一年
java·后端·面试
码事漫谈13 小时前
【精华】C++成员初始化列表完全指南:为什么、何时以及如何正确使用
后端
码事漫谈13 小时前
C++ 强制类型转换:类型安全的多维工具
后端
RainbowSea14 小时前
github 仓库主页美化定制
后端
RainbowSea15 小时前
从 Spring Boot 2.x 到 3.5.x + JDK21:一次完整的生产环境迁移实战
java·spring boot·后端
笨手笨脚の15 小时前
Spring Core常见错误及解决方案
java·后端·spring
计算机毕设匠心工作室15 小时前
【python大数据毕设实战】全球大学排名数据可视化分析系统、Hadoop、计算机毕业设计、包括数据爬取、数据分析、数据可视化、机器学习、实战教学
后端·python·mysql
VX:Fegn089515 小时前
计算机毕业设计|基于Java人力资源管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端·课程设计
荔枝hu15 小时前
springboot和shiro组合引入SseEmitter的一些坑
java·spring boot·后端·sseeitter
老华带你飞16 小时前
健身房|基于springboot + vue健身房管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端