Example analysis of scan usage of php redis

藏色散人
Release: 2023-04-10 20:18:01
forward
3873 people have browsed it

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]
Copy after login

For example

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

Example analysis of scan usage of php redis

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

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;
}
Copy after login

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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template