因业务需要,需要对指定redis的前缀批量删除,如果直接使用keys 命令在数据量比较大的情况下会导致redis集群崩溃或者业务hang住。利用scan通过分页方式来拿到指定的key前缀,在进行相关数据的删除。
之前搜了网上很多文章,发现jedisCluster.getClusterNodes()在jedis的4.x版本获取的对象Map<String, ConnectionPool>,而不是Map<String, JedisPool>。针对这个情况进行代码改造
Connection jedisConnect = pool.getResource();
Jedis jedisNode = new Jedis(jedisConnect);
来获取jedisNode客户段,具体代码如下
public void delStringByScanV2(String keyPrefix) {
ScanParams scanParams = new ScanParams().match(keyPrefix + "*").count(50);
redisService.getJedis().getClusterNodes().values().stream()
.forEach(pool -> {
boolean done = false;
String cursor = SCAN_POINTER_START;
try (Connection jedisConnect = pool.getResource(); Jedis jedisNode = new Jedis(jedisConnect)) {
while (!done) {
ScanResult<String> resp = jedisNode.scan(cursor, scanParams);
log.info("Key: " + resp.getResult() + ", Value: " + resp.getCursor() +",cluster: " + pool.getResource().toString());
//删除redis的key
resp.getResult().stream().map(key -> redisService.getJedis().del(key)).count();
cursor = resp.getCursor();
if (SCAN_POINTER_START.equals(cursor)) {
done = true;
}
}
}
});
}
其中getJedis返回的是?JedisCluster
public JedisCluster getJedis() {
if (jedis == null) {
logger.info("Jedis connection is lost, need to reconnect " + redisNodes);
createRedisConn();
}
return jedis;
}