【问题标题】:Not able Scan using redis template无法使用 redis 模板扫描
【发布时间】:2015-07-27 02:04:19
【问题描述】:

我正在尝试使用 SCAN http://redis.io/commands/scan 来遍历 redis 中存在的所有键。但是spring提供的Redis模板没有scan()方法。使用上面有什么技巧吗?

谢谢

【问题讨论】:

    标签: redis spring-data-redis


    【解决方案1】:

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

    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.4.0 版(spring-data-redis)开始可用。
    • 我收到 java.util.NoSuchElementException
    • @coolscitist 存在一个问题,即 redis 为扫描交互返回一个空结果,该结果被解释错误(请参阅DATAREDIS-417)。将在下一个版本中修复。
    • redis.clients.jedis.exceptions.JedisException:无法将资源返回到池中。这个异常总是因为游标被显式关闭而发生?
    【解决方案2】:
    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;
            });
    

    【讨论】:

    • 您能否在您的代码中添加一些解释,以便我的新手可以理解为什么这样可以解决问题?
    猜你喜欢
    • 2015-12-20
    • 2016-05-30
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    相关资源
    最近更新 更多