redisTemplate 模糊查询
场景
线上有百万级别的 key , 要求模糊查询,并删除
模糊查询
想当然就是 keys
, 不过 大量的 key 加载会阻塞 redis, 影响其他业务调用 , 所以选择 scan
public Set<String> fuzzySearch(String pattern) {
Set<String> keys = new HashSet<>();
Cursor<byte[]> cursor = null;
try {
cursor = (Cursor) redisTemplate.execute((RedisCallback) redisConnection -> redisConnection.scan(ScanOptions.scanOptions().match(pattern).count(10000).build()));
if (cursor==null || cursor.getCursorId()==0){
return Collections.emptySet();
}
while (cursor.hasNext()) {
keys.add(new String(cursor.next()));
}
} catch (Exception e) {
} finally {
if (cursor != null) {
try {
cursor.close();
} catch (IOException e) {
//....
}
}
}
return keys;
}
scan 并不能解决CUP竞争问题,只是优化内存加载问题!!