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);
}
相关推荐
明月_清风36 分钟前
为什么最近开始关注 JEV?几个实战案例告诉你答案
人工智能·后端
GetcharZp1 小时前
5 分钟拥有自己的 S3:RustFS 上手(MinIO 的 Rust 替代,Apache 2.0 可商用)
后端
行百里er2 小时前
Redis 版本演进、新特性与协议那些事儿
redis·后端
Joy T2 小时前
Spring AI 2.0 Agent 进阶:Memory、State 与 Context Engineering 常见技术全景
java·人工智能·后端·spring·agent入门·agent state
打工仔折腾 AI3 小时前
FastAPI 从本机到生产服务器:Nginx+Gunicorn+Uvicorn 完整部署实录
人工智能·后端·python·nginx·fastapi·gunicorn
IT_陈寒3 小时前
Java空指针这次真把我坑惨了
前端·人工智能·后端
moMo4 小时前
LangChain 到 LangGraph: RAG 知识库改造
后端
用户574385305114 小时前
元数据驱动的通用 CRUD 后端框架 (3- createBusiness 工厂:三层装配 + 一行出 REST)
后端
高级程序源4 小时前
django大学生创新创业项目管理系统94923-计算机课程设计、毕业设计
javascript·vue.js·spring boot·后端·python·django·课程设计