redis中scan和keys的区别
2024-09-24 16:49:29
scan和keys的区别
redis的keys命令,通来在用来删除相关的key时使用,但这个命令有一个弊端,在redis拥有数百万及以上的keys的时候,会执行的比较慢,更为致命的是,这个命令会阻塞redis多路复用的io主线程,如果这个线程阻塞,在此执行之间其他的发送向redis服务端的命令,都会阻塞,从而引发一系列级联反应,导致瞬间响应卡顿,从而引发超时等问题,所以应该在生产环境禁止用使用keys和类似的命令smembers,这种时间复杂度为O(N),且会阻塞主线程的命令,是非常危险的。
keys命令的原理就是扫描整个redis里面所有的db的key数据,然后根据我们的通配的字符串进行模糊查找出来。官网详细的介绍如下。
https://redis.io/commands/KEYS
取而代之的,如果需要查找然后删除key的需求,那么在生产环境我们应该使用scan命令,代替keys命令,同样是O(N)复杂度的scan命令,支持通配查找,scan命令或者其他的scan如SSCAN ,HSCAN,ZSCAN命令,可以不用阻塞主线程,并支持游标按批次迭代返回数据,所以是比较理想的选择。keys相比scan命令优点是,keys是一次返回,而scan是需要迭代多次返回。
https://redis.io/commands/scan
但scan命令的也有缺点,返回的数据有可能重复,需要我们在业务层按需要去重,scan命令的游标从0开始,也从0结束,每次返回的数据,都会返回下一次游标应该传的值,我们根据这个值,再去进行下一次的访问,如果返回的数据为空,并不代表没有数据了,只有游标返回的值是0的情况下代表结束。
redis命令例子如下:
scan 0 match my*key count 10000
在Java项目里面,使用jedis执行scan命令的模板例子如下:
Jedis jedis = getJedis(); //存储返回的结果 Set<String> result=new HashSet<String>(); //设置查询的参数 ScanParams scanParams=new ScanParams().count(scanLimitSize).match(pattern); //游标的开始 String cur=ScanParams.SCAN_POINTER_START; do{ //遍历每一批数据 ScanResult<String> scan=jedis.scan(cur, scanParams); //得到结果返回 List<String> scanResult =scan.getResult(); result.addAll(scanResult); //获取新的游标 cur=scan.getStringCursor(); //判断游标迭代是否结束 }while (!cur.equals(ScanParams.SCAN_POINTER_START)); //返回结果 return result;
java中使用redisTemplate实现
- 方法一:通过 scan 先获取以“message:xxx:yyy:id: ”为 Key 前缀的所有完整的 Key,再通过获取到的 Key 拿所有的 Value
/**
* 通过 key 获取 value
* <p>
* pattern:message:xxx:yyy:id:
* limit:每次限制筛选的数量,不建议 Integer.MAX_VALUE
*/
public List<String> assembleScanValues(String pattern, Long limit) {
List<String> values = assembleScanKeys(pattern, limit);
return redisTemplate.opsForValue().multiGet(values).stream().filter(StringUtils::isNotBlank).collect(toList());
} /**
* 组装 scan 的结果集
*/
public List<String> assembleScanKeys(String pattern, Long limit) {
HashSet<String> set = new HashSet<>();
Cursor<String> cursor = scan(redisTemplate, pattern, limit);
while (cursor.hasNext()) {
set.add(cursor.next());
}
try {
cursor.close();
} catch (Exception e) {
log.error("关闭 redis connection 失败");
}
return set.stream().map(String::valueOf).collect(toList());
}
/**
* 自定义 redis scan 操作
*/
private Cursor<String> scan(RedisTemplate redisTemplate, String pattern, Long 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 org.springframework.dao.DataAccessException {
return new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize);
}
});
- 方法二:通过 scan 获取到 Key 的同时,去获取对应的 Value
/**
* 组装分布式缓存中的 value 值
* <p>
* pattern:message:xxx:yyy:id:
* limit:每次限制筛选的数量,不建议 Integer.MAX_VALUE
*/
public List<String> assembleScanValues(String pattern, Long limit) {
Set<String> valueSet = scan(redisTemplate, pattern, limit);
return valueSet.stream().map(String::valueOf).collect(toList());
} /**
* 组装 scan 的结果集
*/
private Set<String> scan(RedisTemplate redisTemplate, String pattern, Long limit) {
return (Set<String>) redisTemplate.execute(new RedisCallback<Set<String>>() {
@Override
public Set<String> doInRedis(RedisConnection connection) throws DataAccessException {
Set<String> valueSet = new HashSet<>();
try (Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder()
.match(pattern).count(limit).build())) {
while (cursor.hasNext()) {
byte[] bytes = connection.get(cursor.next());
String value = String.valueOf(redisTemplate.getValueSerializer().deserialize(bytes));
valueSet.add(value);
}
} catch (IOException e) {
log.error(String.format("get cursor close {%s}", e));
}
return valueSet;
}
});
}
参考及汇总自:https://qimok.cn/856.html https://cloud.tencent.com/developer/article/1440487
最新文章
- [译]学习IPython进行交互式计算和数据可视化(五)
- canvas绘制
- Oracle数据库备份与恢复
- Python的平凡之路(11)
- python urllib2使用心得
- 如何让Visual Studio 清除最近打开项目 关闭上次未关闭的标签窗口
- 配置你的Editor
- 【BZOJ 5222】[Lydsy2017省队十连测]怪题
- python的日志配置
- 解决mysql中文乱码问题?
- 记号一次更换IBM X3650M4主板后RAID无法启动的解决
- mysql order by 排序的问题
- R12.1.3 &; R12.2.X 注册客户化应用
- PHP适配器模式
- import Tkinter error, no module named tkinter: ";Python may not be configured for Tk”
- django models实际操作中遇到的一些问题
- 菜鸟学习Spring Web MVC之一
- 子窗口访问父页面iframe中的iframe,top打开的子窗口访问父页面中的iframe中的iframe
- 定义了一个UIImageView如何使加载的图片不会失真 UIImageView的Frame值是固定的
- 常见HTTP状态码(200、301、302、500等) 释义