Home  >  Article  >  Database  >  How to use redis scan? (Attached code example)

How to use redis scan? (Attached code example)

藏色散人
藏色散人forward
2021-12-16 14:19:072584browse

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]

For example,

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

How to use redis scan? (Attached code example)

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

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

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!

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