如何在Lettuce Redis客户端库中初始化MapScanCursor?

时间:2017-06-15 22:34:57

标签: java redis lettuce

我正在尝试使用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”?

1 个答案:

答案 0 :(得分:1)

您有两种选择:

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

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的方法。