使用需求: 对大批量keys进行操作会阻塞Redis,导致Redis无法正常提供服务,所以一般使用Scan迭代进行批量操作,而不是一次性进行操作
常用使用场景: 批量删除keys, 对符合某些规则的key迭代进行批量操作
@org.junit.Test
public void scanSM() {
Jedis jedis = null;
try {
jedis = new Jedis("192.168.15.151", 6379);
for (int i = 0; i < 100; i++) {
jedis.set("key" + i, i + "");
}
for (int i = 0; i < 100; i++) {
jedis.set("aaa" + i, i + "");
}
List<String> list = getScan(jedis, "key*");
System.out.println("长度:"+list.size()+" \nlist:"+list);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis) {
jedis.close();
}
}
}
public static List<String> getScan(Jedis jedis, String key) {
List<String> list = new ArrayList<>();
ScanParams params = new ScanParams();
params.match(key);
params.count(2);
String cursor = "0";
while (true) {
ScanResult scanResult = jedis.scan(cursor, params);
List<String> elements = scanResult.getResult();
if (elements != null && elements.size() > 0) {
list.addAll(elements);
}
cursor = scanResult.getStringCursor();
System.out.println("cursor: "+cursor);
if ("0".equals(cursor)) {
break;
}
}
return list;
}