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