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);
}
相关推荐
阿在在3 小时前
Spring 系列(三):Spring PostProcessor 顶级扩展接口全解析
java·后端·spring
祈安_4 小时前
深入理解指针(三)
c语言·后端
听风者就是我4 小时前
(LLM系列)文档切分策略详解:Chunk Size 如何决定 RAG 系统的检索天花板
后端
野犬寒鸦4 小时前
ArrayList扩容机制深度解析(附时序图详细讲解)
java·服务器·数据结构·数据库·windows·后端
逆境不可逃4 小时前
【从零入门23种设计模式03】创建型之建造者模式(简易版与导演版)
java·后端·学习·设计模式·职场和发展·建造者模式
汤姆yu5 小时前
基于springboot的健身爱好者打卡与互动交流系统
java·spring boot·后端
计算机毕设VX:Fegn08956 小时前
计算机毕业设计|基于springboot + vue连锁门店管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
南部余额7 小时前
SpringBoot文件上传全攻略
java·spring boot·后端·文件上传·multipartfile
汤姆yu8 小时前
基于springboot的智能民宿预定与游玩系统
java·spring boot·后端
琢磨先生David8 小时前
有了AI,还需要学Springboot吗?
人工智能·spring boot·后端