我试图用莴苣的同步命令来做一个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”?

最佳答案

你有两个选择:
要回答您的问题,只需用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(请参阅莴苣4.4),这是一个Iterator,涵盖了redisSCAN使用的复杂性:
ScanIterator<KeyValue<String, String>> iterator = ScanIterator.hscan(redisCommands, key);

while (iterator.hasNext()) {

    KeyValue<String, String> next = iterator.next();
    // …
}

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

09-25 20:33