redis的模糊检索有两种方式:
1、使用keys
通配符 * ? []
其匹配的字符跟一般的正则一样。
keys a* 可以匹配以a开头的字符串。
keys语法简单,但是数据量大的时候容易出现超时异常。
2、使用scan
这里使用的是spring的一个模板redisTemplate
private Cursor<String> scan(String pattern, int limit) {
ScanOptions options = ScanOptions.scanOptions().match(pattern).count(limit).build();
RedisSerializer<String> redisSerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
return (Cursor) redisTemplate.executeWithStickyConnection(new RedisCallback() {
@Override
public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
Object obj = new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize);
try {
redisConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
});
}
redisConnection.close();这个是关闭连接,要不然链接数量上限之后会一直阻塞。
接收的是一个Cursor
public List<String> getAll4Value(String keyPatten,int limitCount){
intiParam();
List<String> lstTmp = new ArrayList<>();
Cursor<String> cursor = scan(keyPatten,limitCount);
while (cursor.hasNext()) {
String key = cursor.next();
Object obj = get(key);
if(!StringUtils.isEmpty(obj)){
lstTmp.add(obj.toString());
}
}
return lstTmp;
}
keyPatten:正则表达式接收*、、[]
limitCount:返回的数量