Why use scan instead of keys?

· Since redis is single-threaded, use the keys command. If the key in Redis is very large, the execution time of this command will be very long, which will block the execution of other commands. Therefore, redis should also provide us with another scan command to solve this common scenario.

2. What are the advantages of SCAN?

  1. The time complexity of the scan command is also O(N), but it is repeated and does not block the thread.
  2. The scan command provides the limit parameter to control the maximum number of results to be returned at a time.

These two advantages help us solve the above problem, but the scan command is not perfect, it may return duplicate results, so the client needs to redo. But this is an easy problem to solve, and we can do it with sets.

The Redis Scan command is used to iterate over database keys in a database.

The SCAN command is a cursor based iterator that returns a new cursor to the user each time it is called. The user needs to use the new cursor as the cursor parameter of the SCAN command in the next iteration to continue the previous iteration.

SCAN returns an array of two elements. The first element is a new cursor for the next iteration, and the second element is an array containing all the elements being iterated over. If the new cursor returns 0, the iteration is over.

The following code indicates that 1000 prefixed keys are scanned from redis server and put into set. Count is the number of keys scanned each time, not the number of result sets

 Set<String> keys = redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
            Set<String> keysTmp = new HashSet<>();
            Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder().match(REDIS_KEY_NAME + "*").count(1000).build());
            while (cursor.hasNext()) {
                keysTmp.add(new String(cursor.next()));
            }
            return keysTmp;
        });
Copy the code