Home  >  Article  >  Database  >  How to get all keys in redis

How to get all keys in redis

PHPz
PHPzforward
2023-05-28 15:40:213489browse

keys: Full traverse keys, used to list all keys that meet specific regular string rules. Assuming that redis is in a production environment at this time, using this command will cause hidden dangers. When the amount of redis data is relatively large:

keys will return all qualified keys at once, so it will cause redis to be stuck.

SCAN iterator is based on cursor, and the last cursor needs to be used to continue the previous iteration process. Using cursor 0 as the starting point, perform a new traversal operation and continue iterating until the command returns to cursor 0 to complete the entire traversal.

This command does not guarantee that each execution will return a given number of elements, and may even return 0 elements. However, as long as the cursor is not 0, the program will not think that the SCAN command has ended, but the returned elements The quantity is likely to match the count parameter. In addition, SCAN supports fuzzy queries.

1.keys cmos-cache package

redisCacheService.keys(String pattern);

2.scan method

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;
}

The above is the detailed content of How to get all keys in redis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete