[英]Jedis scan doesn't find any key
我想使用Jedis通过以下代码片段从Redis集群中获取所有密钥:
public void testRedis() {
String key = "*";
ScanParams scanParams = new ScanParams().count(1000).match("{*}");
String cur = SCAN_POINTER_START;
do {
ScanResult<String> scanResult = getRedisCluster().scan(cur, scanParams);
scanResult.getResult().stream().forEach(System.out::println);
cur = scanResult.getStringCursor();
} while (!cur.equals(SCAN_POINTER_START));
}
我的问题是此解决方案不会返回任何结果。 即使我为现有键指定了匹配模式,它仍然无法正常工作。 我尝试使用get命令获取特定的键,该命令返回的值没有任何错误,因此连接似乎很好。
有什么建议吗? (我的线索之一是match参数在等待“花括号”,因此我必须在其中添加,但是我还没有看到在互联网上的任何地方都使用这种方法。)
您可以通过从每个节点获取密钥并统一它们来获取集群的所有密钥。
getClusterNodes()
方法getClusterNodes()
上用场,它返回所有群集节点的映射。
这是使用SCAN
的实现,类似于您的尝试:
public void testRedis() {
ScanParams scanParams = new ScanParams().count(1000);
Set<String> allKeys = new HashSet<>();
getRedisCluster().getClusterNodes().values().forEach((pool) -> {
String cur = ScanParams.SCAN_POINTER_START;
do {
try (Jedis jedis = pool.getResource()) {
ScanResult<String> scanResult = jedis.scan(cur, scanParams);
allKeys.addAll(scanResult.getResult());
cur = scanResult.getStringCursor();
}
} while (!cur.equals(ScanParams.SCAN_POINTER_START));
});
allKeys.stream().forEach(System.out::println);
}
更新:您可以获得至少1000个密钥后,可以检查条件以立即停止迭代。
public void testRedis() {
ScanParams scanParams = new ScanParams().count(1000);
Set<String> allKeys = new HashSet<>();
for (JedisPool pool : getRedisCluster().getClusterNodes().values()) {
String cur = ScanParams.SCAN_POINTER_START;
do {
try (Jedis jedis = pool.getResource()) {
ScanResult<String> scanResult = jedis.scan(cur, scanParams);
allKeys.addAll(scanResult.getResult());
cur = scanResult.getStringCursor();
}
if (allKeys.size() >= 1000) break;
} while (!cur.equals(ScanParams.SCAN_POINTER_START));
if (allKeys.size() >= 1000) break;
}
allKeys.stream().forEach(System.out::println);
}
match
方法的模式应为"*"
而不是"{*}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.