【问题标题】:How do you initialize the MapScanCursor in Lettuce Redis client library?如何在 Lettuce Redis 客户端库中初始化 MapScanCursor?
【发布时间】:2017-06-15 22:34:57
【问题描述】:

我正在尝试使用 Lettuce 的同步命令进行 HSCAN。问题是我无法弄清楚初始化 MapScanCursor 的正确方法。我的构造函数没有成功,MapScanCursor.INITIAL 给出了ScanCursor 类型(也没有运气将其转换为MapScanCursor)。

这是一个例子:

RedisClient redisClient = RedisClient.create("redis://" + url + ":" + port);
RedisHashCommands<String, String> redisCommands = redisClient.connect().sync();
List<String> fields = new LinkedList<>();

MapScanCursor<String, String> scanCursor = ?

do {
    scanCursor = redisCommands.hscan(key, scanCursor);
    fields.addAll(scanCursor.getMap().keySet());
} while (!scanCursor.isFinished());

我应该如何初始化“scanCursor”?

【问题讨论】:

    标签: java redis lettuce


    【解决方案1】:

    你有两个选择:

    要回答您的问题,请使用 hscan(key) 初始化 scanCursor

    MapScanCursor<String, String> scanCursor = null;
    
    do {
        if (scanCursor == null) {
            scanCursor = redisCommands.hscan(key);
        } else {
            scanCursor = redisCommands.hscan(key, scanCursor);
        }
        fields.addAll(scanCursor.getMap().keySet());
    } while (!scanCursor.isFinished());
    

    或者,您可以使用 ScanIterator(参见 Lettuce 4.4),它是一个 Iterator,涵盖了 Redis SCAN 用法的复杂性:

    ScanIterator<KeyValue<String, String>> iterator = ScanIterator.hscan(redisCommands, key);
    
    while (iterator.hasNext()) {
    
        KeyValue<String, String> next = iterator.next();
        // …
    } 
    

    更新

    根据 tcfritchman 的评论更新了基于 do…while 的方法。

    【讨论】:

    • 感谢您提供出色替代方案的有用答案。这解决了我的问题。一个小问题是,当使用第一个选项时,您必须在第二次调用hscan 之前检查!scanCursor.isFinished()。否则,如果扫描在第一次调用时完成,您将收到错误消息。例如。 scanCursor = redisCommands.hscan(key); while (!scanCursor.isFinished()) {scanCursor = redisCommands.hscan(key, scanCursor); fields.addAll(scanCursor.getMap().keySet()); }
    猜你喜欢
    • 2021-06-28
    • 2015-12-13
    • 1970-01-01
    • 2020-12-01
    • 2017-04-24
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多