正文

redis获取所有key的方法(从redis中获取数据)学会了吗

文章摘要

这篇文章描述了一个Java静态方法`getAllKey`,用于从Redis集群节点中获取所有符合条件的关键字,并将它们存储在集合中返回。方法通过`RedisCacheService`获取Jedis集群,并使用`getClusterNodes`获取集群节点。对于每个节点,调用`scan`方法遍历数据,使用游标`cur`控制扫描过程,直到游标为"0"时结束扫描。扫描结果中的数据被添加到返回的集合`binKeys`中。该方法的核心功能是通过Redis集群进行高效的关键词数据收集。

public static Set<String> getAllKey(String match,int count){ //返回集 Set<String> binKeys=new HashSet<>(); //封装scan查询参数 ScanParams param=new ScanParams().match(match).count(count); //获取查询对象 RedisCacheServiceImpl redisCacheSer=(RedisCacheServiceImpl)RedisCacheService; JedisCluster jedisClu=redisCacheSer.getJedisCluster(); //getClueterNodes获取集群节点,从各个集群中获取值进行遍历 jedisClu.getClusterNodes().values().stream().forEach(pool->{ boolean done=false;// String cur=”0″;//游标,以0开始,返回0代表一次结束 try(Jedis jedisNode=pool.getResource()){ while(!done){ ScanResult<String> scanResult=jedisNode.scan(cur,param); cur=scanResult.getStringCursor(); if(“0”.equals(cur){done=true}; List<String> result=scanResult.getResult(); result.foreach(data->{binKeys.add(data)}); } } }); return binKeys; }