Home  >  Article  >  Database  >  How to use scan to replace keys in Redis

How to use scan to replace keys in Redis

藏色散人
藏色散人forward
2020-01-28 14:06:323630browse

How to use scan to replace keys in Redis

We all know that when searching for Redis keys, you can use keys pattern. However, when there are too many keys, the efficiency of the keys command is very low. If used directly online, it may even cause production problems. Accident, at this time, we might as well use the scan command.

The SCAN command is a cursor-based iterator (cursor based iterator):

Every time the SCAN command is called, a new cursor will be returned to the user. The user needs to use this new cursor as the cursor parameter of the SCAN command in the next iteration to continue the previous iteration process.

When the cursor parameter of the SCAN command is set to 0, the server will start a new iteration, and when the server returns a cursor with a value of 0 to the user, it indicates that the iteration has ended.

Generate key

<?php
// 生成1000个
$redis = new \Redis();
$redis->connect(&#39;127.0.0.1&#39;, 6379, 10);
$redis->select(2);
$arr = [
    &#39;rwer&#39;,
    &#39;24erw&#39;,
    &#39;rterq4&#39;,
    &#39;sdgfd5&#39;,
    &#39;dgsdg&#39;,
    &#39;sfst&#39;,
];
for ($i=0; $i<1000; $i++) {
    $redis->set(md5($i.$arr[$i%6]), md5($arr[$i%6].&#39;sdfsd&#39;));
}
echo "OK".PHP_EOL;

keys View number

keys c*

How to use scan to replace keys in Redis

Use scan in Redis to replace keys

scan traverse

<?php
$redis = new \Redis();
$redis->connect(&#39;127.0.0.1&#39;, 6379, 10);
$redis->select(2);
$iterator = null;
// 遍历前缀
$pattern = &#39;c*&#39;;
$count = 100;
// 务必设置,如果没扫描到,继续扫描,而不是返回空,否则while直接退出,遍历就会不准确
$redis->setOption(\Redis::OPT_SCAN, \Redis::SCAN_RETRY);
$total = [];
$i = 0;
// $count可以不设置,非必需参数
while($arr = $redis->scan($iterator, $pattern, $count)) {
    $arrVal = $redis->mget($arr);
    $ret = array_combine($arr, $arrVal);
    $total = array_merge($total, $ret);
    $i++;
}
// var_dump($total);
var_dump($i);
echo count($total).PHP_EOL;

Use in Redis scan replace keys

How to use scan to replace keys in Redis

Of course you can also not use \Redis::OPT_SCAN, \Redis::SCAN_RETRY These two parameters loop by themselves to determine whether the return value is false, and the traversal can also be successful.

For more redis knowledge, please pay attention to the redis database tutorial column.

The above is the detailed content of How to use scan to replace keys in 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