redis模糊查询redis中的key
方式一:使用keys命令
/**
* 查找匹配的key
*
* @param pattern
* @return
*/
public Set<String> keys(String pattern) {
return redisTemplate.keys(pattern);
}
方式二:使用san命令
/**
* 查找匹配的key
*
* @param pattern
* @return
*/
public List<String> scanKeysByPattern(String pattern) {
ScanOptions options = ScanOptions.scanOptions().match(pattern).build();
Cursor<String> cursor = redisTemplate.scan(options);
List<String> matchedKeys = new ArrayList<>();
while (cursor.hasNext()) {
String key = cursor.next();
matchedKeys.add(key);
}
return matchedKeys;
}
在redis里,允许模糊查询key
有3个通配符 *, ? ,[]
*: 通配任意多个字符
?: 通配单个字符
[]: 通配括号内的某1个字符
测试效率
@GetMapping("/matchKeys")
public Object matchKeys(@RequestParam String keyPrefix) {
StopWatch stopWatch = new StopWatch();
String keyPattern = keyPrefix + "*";
stopWatch.start("--keys--");
Set<String> keys = redisUtil.keys(keyPattern);
stopWatch.stop();
System.out.println("----keys------keys.size=" + keys.size() + "----耗时= " + stopWatch.getLastTaskTimeMillis());
stopWatch.start("--scan--");
List<String> keys1 = redisUtil.scanKeysByPattern(keyPattern);
stopWatch.stop();
System.out.println("----scan----keys.size=" + keys1.size() + "----耗时= " + stopWatch.getLastTaskTimeMillis());
System.out.println("stopWatch.prettyPrint() = " + stopWatch.prettyPrint());
Map<String, Object> resMap = new HashMap<>();
resMap.put("size", keys.size());
resMap.put("taskTime", stopWatch.getLastTaskTimeMillis());
return resMap;
}
虽然KEYS命令可以用来实现模糊查询Key的功能,但需要注意以下几点:
KEYS命令将在整个Redis数据库中执行查询操作,如果数据库中的Key数量庞大,查询的性能可能会受到影响。
在生产环境中,如果需要频繁进行模糊查询,建议使用Redis的有序集合(Sorted Set)来维护索引,以提高查询效率。