直接上代码
/**
* 通过scan模糊删除
* @param pattern
* @return
*/
public Long delScan(String pattern) {
long count = 0;
if (StringUtils.isNotBlank(pattern)) {
Jedis jds = null;
JedisCluster jedisCluster = null;
String key = pattern;
try {
jds = this.getJedis();
jedisCluster = this.getJedisCluster();
ScanParams scanParams = new ScanParams();
scanParams.count(1000);
key = combineKey(this.group, pattern);
if (!key.endsWith(PATTERN_CHAR)) {
key = key + PATTERN_CHAR;
}
scanParams.match(key);
if (Objects.nonNull(jds)) {
count = scanDelKeys(jds, scanParams);
} else if (Objects.nonNull(jedisCluster)){
for (JedisPool pool : jedisCluster.getClusterNodes().values()) {
Jedis jedis = pool.getResource();
if (jedis.info().indexOf("role:master") != -1) {
count += scanDelKeys(jedis, scanParams);
}
}
}
logger.info("成功删除缓存个数 = {},key={}", count, key);
} catch (Exception e) {
logger.error("删除元素数据出错: key={}", key, e);
} finally {
this.shutdown(jds, null, jedisCluster);
}
}
return count;
}
/**
* 使用scan批量删除keys
* @param jds
* @param scanParams
* @return
*/
private Long scanDelKeys(Jedis jds, ScanParams scanParams) {
Set<String> keys = new HashSet<>();
String cursor = ScanParams.SCAN_POINTER_START;
long count = 0;
do {
//使用hscan命令获取1000条数据,使用cursor游标记录位置,下次循环使用
ScanResult<String> scanResult = jds.scan(cursor, scanParams);
List<String> keyList = scanResult.getResult();
if (CollectionUtils.isNotEmpty(keyList)) {
keys.addAll(keyList);
}
// 返回0 说明遍历完成
cursor = scanResult.getCursor();
} while (!ScanParams.SCAN_POINTER_START.equals(cursor));
// 删除keys
if (CollectionUtils.isNotEmpty(keys)) {
for (String key : keys) {
count += jds.del(key);
}
}
return count;
}
测试结果