如何在 Lettuce Redis 客户端库中初始化 MapScanCursor?
How do you initialize the MapScanCursor in Lettuce Redis client library?
我正在尝试使用 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"?
您有两个选择:
要回答您的问题,请将 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
的方法。
我正在尝试使用 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"?
您有两个选择:
要回答您的问题,请将 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
的方法。