Search code examples
redisspring-data-redis

Not able Scan using redis template


I am trying to use SCAN http://redis.io/commands/scan to iterate over all the keys present in redis. But the Redis template provided by spring do not have any scan() method. Is there any trick to use the above?

Thanks


Solution

  • You can use a RedisCallback on RedisOperations to do so.

    redisTemplate.execute(new RedisCallback<Iterable<byte[]>>() {
    
      @Override
      public Iterable<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
    
        List<byte[]> binaryKeys = new ArrayList<byte[]>();
    
        Cursor<byte[]> cursor = connection.scan(ScanOptions.NONE);
        while (cursor.hasNext()) {
          binaryKeys.add(cursor.next());
        }
    
        try {
          cursor.close();
        } catch (IOException e) {
          // do something meaningful
        }
    
        return binaryKeys;
      }
    });