jedis运用scan删除正则匹配的key
我们都知道用keys *进行查询key的时候会进行堵塞,导致redis整体不可用,而使用scan命令则不会.
RedisServiceImpl中scan的内容为
@Override
public ScanResult scan(String cursor, ScanParams params) {
return execute(new RedisFunction<ScanResult, Jedis>() {
@Override
public ScanResult callback(Jedis jedis) {
return jedis.scan(cursor,params);
}
});
}
然后定义一个工具类
public class RedisUntil {
public static List<String> getScan(RedisService redisService,String key) {
List<String> list = new ArrayList<>();
ScanParams params = new ScanParams();
params.match(key);
params.count(100);
while (true) {
ScanResult scanResult = redisService.scan("0",params);
List<String> elements = scanResult.getResult();
if (elements != null && elements.size() > 0) {
list.addAll(elements);
}
String cursor = scanResult.getStringCursor();
if ("0".equals(cursor)) {
break;
}
}
return list;
}
}
使用该工具类进行批量删除,假设我们要删除的是以"userpage:"为前缀
List<String> keyList = RedisUntil.getScan(redisService,"userpage:*");
for (String key:keyList) {
redisService.del(key);
}