【问题标题】:Redis iterate over key groupsRedis 迭代关键组
【发布时间】:2015-01-18 12:16:47
【问题描述】:

我想检查我在 redis 中的所有键是否正确。

我将密钥存储在这样的组中:

userid:fname
userid:lname
userid:age
...

我想通过按用户 ID 对它们进行分组来迭代它们,然后从 fname、lname 和 age 中检查每个组。

我该怎么做?

【问题讨论】:

  • SCAN 命令可能是你需要的
  • 你能给我举个例子吗?我在 Java 中使用 Jedis。
  • 肯定可以找到redis命令文档和jedis的文档?
  • 这是项目页面github.com/xetorthio/jedis 基本上和Jedis对象中的redis功能一样。
  • 您好,我尝试使用 SCAN 命令,但我似乎无法理解如何正确使用它,您可以给我举个例子吗?

标签: redis jedis


【解决方案1】:
ScanParams params = new ScanParams();
params.match("userid:fname*");

// Use "0" to do a full iteration of the collection.  
ScanResult<String> scanResult = jedis.scan("0", params);
List<String> keys = scanResult.getResult();

对 lname 和 age 重复上述代码。或者,匹配user:id,然后使用正则表达式过滤组并遍历keys

编辑:对于大型集合(数百万个键),a scan result will return a few tens of elements。相应地调整您的代码以继续扫描,直到扫描完整个密钥集合:

ScanParams params = new ScanParams();
params.match("userid:fname*");

// An iteration starts at "0": http://redis.io/commands/scan
ScanResult<String> scanResult = jedis.scan("0", params);
List<String> keys = scanResult.getResult();
String nextCursor = scanResult.getStringCursor();
int counter = 0;

while (true) {
    for (String key : keys) {
        addKeyToProperGroup(key);
    }

    // An iteration also ends at "0"
    if (nextCursor.equals("0")) {
        break;
    }

    scanResult = jedis.scan(nextCursor, params);
    nextCursor = scanResult.getStringCursor();
    keys = scanResult.getResult();
}

【讨论】:

    【解决方案2】:

    您可以使用Redisson Redis 客户端提供的基于Redis 的java.util.Iteratorjava.lang.Iterable 接口。

    这是一个例子:

    RedissonClient redissonClient = RedissonClient.create(config);
    
    RKeys keys = redissonClient.getKeys();
    
    // default batch size on each SCAN invocation is 10
    for (String key: keys.getKeys()) {
    ...
    }
    
    // default batch size on each SCAN invocation is 250
    for (String key: keys.getKeys(250)) {
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-30
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 2017-02-09
      • 2015-03-30
      • 2018-09-27
      • 2012-07-07
      • 1970-01-01
      相关资源
      最近更新 更多