Redis 中如何使用 scan 替換 keys

Redis 中如何使用 scan 替換 keys

我們都知道查找 redis 的鍵時(shí),可以使用 keys pattern,但當(dāng) key 太多時(shí),keys 命令的效率就很低,如果在線上直接使用,甚至可能發(fā)生生產(chǎn)事故,這時(shí)候,我們不妨使用 scan 命令。

SCAN 命令是一個(gè)基于游標(biāo)的迭代器(cursor based iterator):?

SCAN 命令每次被調(diào)用之后, 都會(huì)向用戶返回一個(gè)新的游標(biāo), 用戶在下次迭代時(shí)需要使用這個(gè)新游標(biāo)作為 SCAN 命令的游標(biāo)參數(shù), 以此來(lái)延續(xù)之前的迭代過(guò)程。

當(dāng) SCAN 命令的游標(biāo)參數(shù)被設(shè)置為 0 時(shí), 服務(wù)器將開(kāi)始一次新的迭代, 而當(dāng)服務(wù)器向用戶返回值為 0 的游標(biāo)時(shí), 表示迭代已結(jié)束。

生成 key

<?php // 生成1000個(gè) $redis = new Redis(); $redis->connect('127.0.0.1',?6379,?10); $redis-&gt;select(2); $arr?=?[ ????'rwer', ????'24erw', ????'rterq4', ????'sdgfd5', ????'dgsdg', ????'sfst', ]; for?($i=0;?$iset(md5($i.$arr[$i%6]),?md5($arr[$i%6].'sdfsd')); } echo?"OK".PHP_EOL;

keys 查看個(gè)數(shù)

keys c*

Redis 中如何使用 scan 替換 keys

Redis中使用scan替換keys

scan 遍歷

<?php $redis = new Redis(); $redis->connect('127.0.0.1',?6379,?10); $redis-&gt;select(2); $iterator?=?null; //?遍歷前綴 $pattern?=?'c*'; $count?=?100; //?務(wù)必設(shè)置,如果沒(méi)掃描到,繼續(xù)掃描,而不是返回空,否則while直接退出,遍歷就會(huì)不準(zhǔn)確 $redis-&gt;setOption(Redis::OPT_SCAN,?Redis::SCAN_RETRY); $total?=?[]; $i?=?0; //?$count可以不設(shè)置,非必需參數(shù) while($arr?=?$redis-&gt;scan($iterator,?$pattern,?$count))?{ ????$arrVal?=?$redis-&gt;mget($arr); ????$ret?=?array_combine($arr,?$arrVal); ????$total?=?array_merge($total,?$ret); ????$i++; } //?var_dump($total); var_dump($i); echo?count($total).PHP_EOL;

Redis中使用scan替換keys

Redis 中如何使用 scan 替換 keys

當(dāng)然你也可以不使用 Redis::OPT_SCAN, Redis::SCAN_RETRY 這兩個(gè)參數(shù),自行循環(huán),判斷返回值是不是 false,也能遍歷成功。

更多redis知識(shí)請(qǐng)關(guān)注redis數(shù)據(jù)庫(kù)教程欄目。

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊11 分享