从Redis获取密钥

Bhupesh Mathur:

在Redis中是否可以一次获取n个键?

我在Redis中有超过一百万个密钥,我想准备一个每个100k记录的csv文件。我想获取10万个密钥并准备文件。

Harihar Das:

您可以使用SCANCOUNT选项的命令链接

以下代码示例使用jedis作为Redis客户端。

    // Assuming redis is running on port 32768 on localhost
    // insert some records
    Jedis jedis = new Jedis("localhost", 32768);
    jedis.set("foo1", "bar1");
    jedis.set("foo2", "bar2");
    jedis.set("foo3", "bar3");
    jedis.set("foo4", "bar4");
    jedis.set("foo5", "bar5");

    // first value of cursor must be "0"
    String cursor = "0";

    // fetch 2 keys in every scan
    ScanParams scanParams = new ScanParams().count(2);

    do {
        ScanResult<String> scanResult = jedis.scan(cursor, scanParams);

        System.out.println("Keys for cursor ---> " + cursor);
        scanResult.getResult().forEach((key) -> {
            System.out.println("Key = " + key);
        });

        cursor = scanResult.getCursor();
    } while (!"0".equals(cursor));

在这里,我在scan命令的每次迭代中都获取2个密钥。中返回的光标值ScanResult作为输入发送到下一个扫描命令。如果没有更多结果,则光标值为“ 0”。这用于发信号通知for循环的终止。

我在运行此示例时看到了以下输出。

Keys for cursor ---> 0
Key == foo1
Key == foo3
Keys for cursor ---> 4
Key == foo2
Key == foo
Keys for cursor ---> 1
Key == foo5
Key == foo4
Keys for cursor ---> 5

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章