我正在尝试使用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”?
答案 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
的方法。