我想检查redis中的所有密钥是否正确。
我将密钥存储在这样的组中:
userid:fname
userid:lname
userid:age
...
我想通过userid对它们进行分组来迭代它们,然后从fname,lname和age中检查每个组。
我该怎么做?
答案 0 :(得分:13)
ScanParams params = new ScanParams();
params.match("userid:fname*");
// Use "0" to do a full iteration of the collection.
ScanResult<String> scanResult = jedis.scan("0", params);
List<String> keys = scanResult.getResult();
重复上面的lname和age代码。或者,匹配user:id
,然后使用正则表达式过滤组并迭代keys
。
编辑:对于大型馆藏(数百万个键),a scan result will return a few tens of elements。相应地调整代码以继续扫描,直到扫描完整个键集合为止:
ScanParams params = new ScanParams();
params.match("userid:fname*");
// An iteration starts at "0": http://redis.io/commands/scan
ScanResult<String> scanResult = jedis.scan("0", params);
List<String> keys = scanResult.getResult();
String nextCursor = scanResult.getStringCursor();
int counter = 0;
while (true) {
for (String key : keys) {
addKeyToProperGroup(key);
}
// An iteration also ends at "0"
if (nextCursor.equals("0")) {
break;
}
scanResult = jedis.scan(nextCursor, params);
nextCursor = scanResult.getStringCursor();
keys = scanResult.getResult();
}
答案 1 :(得分:0)
您可以使用Redisson Redis客户端提供的基于Redis的java.util.Iterator
和java.lang.Iterable
接口。
这里是一个例子:
RedissonClient redissonClient = RedissonClient.create(config);
RKeys keys = redissonClient.getKeys();
// default batch size on each SCAN invocation is 10
for (String key: keys.getKeys()) {
...
}
// default batch size on each SCAN invocation is 250
for (String key: keys.getKeys(250)) {
...
}