Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 829
Global Warrior Avatar asked Oct 21 '25 20:10

Global Warrior


2 Answers

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;
  }
});
like image 179
Christoph Strobl Avatar answered Oct 24 '25 19:10

Christoph Strobl


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;
        });
like image 34
running Avatar answered Oct 24 '25 18:10

running



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!