在刪除緩存的時候,我們在一些場景下需要批量刪除,但不確定具體的key值,可通過匹配的方式進行查詢后刪除。
但是使用keys會導致redis服務器宕機。慎用。。。
一般公司也會禁用keys等比較敏感的命令的。
所以工作中會使用scan命令來進行匹配查詢
1
|
SCAN cursor [MATCH pattern] [ COUNT count ] |
比如
1
2
|
# 從游標 0 開始掃描 匹配 test1:* 的鍵值,一次掃描1000條 scan 0 match test1:* count 1000 |
1) 表示下一次掃描的游標值 ,命令行顯示的是字符串類型的。
2)表示本次掃描匹配到的鍵值列表
用php代碼怎么實現呢,舉個例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
function getKeysByPattern( $pattern ) { $keysList = []; while (true){ //@todo 這里的client替換為自己的redis客戶端對象 $keys = $client ->scan( $iterator , $pattern ,1000); $keysList = array_merge ( $keysList , $keys ??[]); if ( $iterator === 0) { //迭代結束,未找到匹配pattern的key break ; } if ( $iterator === null) { //"游標為null了,重置為0,繼續掃描" $iterator = "0" ; } } $keysList = array_unique ( $keysList ); return keysList; } |
內容擴展
php redis擴展支持scan命令實現方法
1
2
3
4
5
|
# git clone https: //github.com/phpredis/phpredis # cd phpredis # /opt/php/bin/phpize # ./configure --with-php-config=/opt/php/bin/php-config # make && make install |
到此這篇關于php redis的scan用法實例分析的文章就介紹到這了,更多相關php redis的scan用法內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.php.cn/php-weizijiaocheng-485532.html