Home> Database> Redis> body text

How to use redis scan? (Attached code example)

藏色散人
Release: 2022-01-22 09:09:47
forward
2478 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 it through matching and then delete it.

But using keys will cause the redis server to crash.

Use with caution. . .

General companies will also disable sensitive commands such as keys.

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

How to use redis scan? (Attached code example)

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

How to implement it using php code, for example 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

Recommended learning: "redis video tutorial"

The above is the detailed content of How to use redis scan? (Attached code example). 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!