Home  >  Article  >  Backend Development  >  Example analysis of scan usage of php redis

Example analysis of scan usage of php redis

藏色散人
藏色散人forward
2021-12-08 14:46:263793browse

When deleting the cache, we need to delete it in batches in some scenarios, but we are not sure of the specific key value. We can query and delete it through matching.

But using keys will cause the redis server to crash. Use with caution. . .

General companies will also disable sensitive commands such as keys. [Related recommendations: Redis video tutorial]

So the scan command will be used to perform matching queries at work

SCAN cursor [MATCH pattern] [COUNT count]

For example

# 从游标 0 开始扫描 匹配 test1:* 的键值,一次扫描1000条
scan 0 match test1:* count 1000

Example analysis of scan usage of php redis

1) 表示下一次扫描的游标值 ,命令行显示的是字符串类型的。
2)表示本次扫描匹配到的键值列表

How to implement it using php code, give an example

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;
}

The above is the detailed content of Example analysis of scan usage of php redis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete