无法使用redis模板进行扫描

时间:2015-05-15 08:07:03

标签: redis spring-data-redis

我正在尝试使用SCAN http://redis.io/commands/scan来迭代redis中存在的所有键。但Spring提供的Redis模板没有任何scan()方法。有没有使用上述技巧?

由于

2 个答案:

答案 0 :(得分:8)

您可以RedisCallback使用RedisOperations来执行此操作。

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

答案 1 :(得分:0)

Set<String> keys = (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
            Cursor<byte[]> cursor = null;
            Set<String> keysTmp = new HashSet<>();
            try {
                cursor = connection.scan(new ScanOptions.ScanOptionsBuilder().match(keyPrefix + "*").count(10000).build());
                while (cursor.hasNext()) {
                    keysTmp.add(new String(cursor.next()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (Objects.nonNull(cursor) && !cursor.isClosed()) {
                    try {
                        cursor.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return keysTmp;
        });