好多人不知道在java中如何 使用 Redistemple 操作 scan ,今天我给出一种实现方式:
@Resource(name = "redisTemplate")
private RedisTemplate redisTemplate;
/**
* 删除登录限制redis
* @return
*/
@RequesMapping(value = "/redis/handle")
public JsonResult redisHandle() {
if (StringUtils.equals(currentEnv, Constants.ENV.TEST)) {
final Set keys = scan("smscode:phoneno:*");
if (!ObjectUtils.isEmpty(keys)) {
log.info("delete keys{}", keys);
for (Object key : keys) {
redisTemplate.delete(key);
}
}
}
return JsonResult.buildSuccess();
}
public Set<String> scan(String key) {
return (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
Set<String> keys = Sets.newHashSet();
JedisCommands commands = (JedisCommands) connection.getNativeConnection();
MultiKeyCommands multiKeyCommands = (MultiKeyCommands) commands;
ScanParams scanParams = new ScanParams();
scanParams.match(key);
scanParams.count(1000);
ScanResult<String> scan = multiKeyCommands.scan("0", scanParams);
while (null != scan.getStringCursor()) {
keys.addAll(scan.getResult());
if (!"0".equals(scan.getStringCursor())) {
scan = multiKeyCommands.scan(scan.getStringCursor(), scanParams);
continue;
} else {
break;
}
}
return keys;
});
}