Laravel和Redis扫描 [英] Laravel and redis scan
问题描述
我正在尝试对Laravel使用Redis scan
.我可以发出一个返回10个键的请求,但我希望循环直到所有键都返回.我不确定如何使用laravel进行此操作.目前我有
I am trying to use redis scan
with laravel. I can make a single request which returns 10 keys but I wish to loop until all the keys have been returned. I am unsure how to do this with laravel. Currently I have
$test = Redis::scan(0, 'match', '*keypattern*');
我不知道是否有一种"laravel"方式.
I don't know if there is a 'laravel' way of doing this.
我使用composer导入了predis/predis
并使其可以使用
I used composer to import predis/predis
and got it working with
use Predis\Collection\Iterator;
use Predis;
...
$client = new Predis\Client([
'scheme' => 'tcp',
'host' => 'localhost',
'port' => 6379,
]);
foreach (new Iterator\Keyspace($client, '*keypattern*') as $key) {
$arr[] = $key;
}
但是我想知道幼虫的方式
but I would like to know the laravel way
单个Redis::scan
array(2) {
[0]=>
string(4) "23"
[1]=>
array(10) {
[0]=>
string(19) "key17"
[1]=>
string(19) "key72"
[2]=>
string(76) "key11"
[3]=>
string(19) "key73"
[4]=>
string(19) "key63"
[5]=>
string(19) "key87"
[6]=>
string(19) "key70"
[7]=>
string(19) "key65"
[8]=>
string(19) "key82"
[9]=>
string(19) "key43"
}
}
推荐答案
由于Redis门面将命令直接传递给Predis(或者您可能会说Redis本身),因此这与Redis文档(
As the Redis facade passes commands directly to Predis (or Redis itself you might say), this goes hand in hand with the Redis docs (http://redis.io/commands/scan). You can use the cursor (first array entry) for subsequent calls to iterate until the cursor is zero.
我整理了一种递归方法,以扫描所有条目:
I've put together a recursive approach, to scan all entries:
function scanAllForMatch ($pattern, $cursor=null, $allResults=array()) {
// Zero means full iteration
if ($cursor==="0") {
return $allResults;
}
// No $cursor means init
if ($cursor===null) {
$cursor = "0";
}
// The call
$result = Redis::scan($cursor, 'match', $pattern);
// Append results to array
$allResults = array_merge($allResults, $result[1]);
// Recursive call until cursor is 0
return scanAllForMatch($pattern, $result[0], $allResults);
}
请注意,如果您在类中使用$this
(可能是return $this->scanAllForMatch(...)
),则可能需要在递归之前添加$this
Note that you might need to add $this
before the recursion, if you use this in a class (would be return $this->scanAllForMatch(...)
)
您会这样称呼它:
// Don't pass a cursor yourself!
$allResults = scanAllForMatch('*keypattern*');
这篇关于Laravel和Redis扫描的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!