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);
}
相关推荐
Victor3561 小时前
Netty(7)如何实现基于Netty的TCP客户端和服务器?
后端
Victor3561 小时前
Netty(8)什么是Netty的ChannelPipeline和ChannelHandler?
后端
乘风!2 小时前
NSSM启动tomcat部署Java程序
java·服务器·后端·tomcat
代码无疆2 小时前
学点java字节码更易于理解一些特殊的java语法效果
java·后端
星浩AI3 小时前
AI 并不懂文字,它只认向量:一文搞懂 Embedding
后端
程序员博博3 小时前
这才是vibe coding正确的打开方式 - 手把手教你开发一个MCP服务
javascript·人工智能·后端
90后的晨仔3 小时前
阿里云服务器如何给子账号设置指定具体的那一台服务器?
后端
期待のcode3 小时前
springboot热部署
java·spring boot·后端
expect7g3 小时前
Paimon源码解读 -- FULL_COMPACTION_DELTA_COMMITS
大数据·后端·flink
踏浪无痕4 小时前
周末拆解:QLExpress 如何做到不编译就能执行?
后端·算法·架构