function scanKeys(string $pattern, int $count = 100): array
{
$cursor = null;
$keys = [];
$redis = \support\Redis::connection();
do {
list($cursor, $fetchedKeys) = $redis->scan($cursor, ['MATCH' => $pattern, 'COUNT' => $count]);
// 將當前批次的鍵添加到結果中
$keys = array_merge($keys, $fetchedKeys);
} while ($cursor > 0);
return array_unique($keys);
}
$keys = scanKeys('data:*');
dump($keys);
這里的keys始終返回redis中所有的key,也就是'MATCH' => $pattern 始終是 'MATCH' => '*'
在咨詢了AI后他給出的提示是
游標 $cursor 初始化為 null,但 Redis 的 SCAN 通常期望初始值為 0。
沒有對 $fetchedKeys 的空值進行防護,可能導致合并空數(shù)組時出現(xiàn)問題。
while ($cursor > 0) 可能不完全正確,因為 Redis 的游標可能返回非整數(shù)值(如字符串),應檢查 $cursor !== 0。
AI給出修改后的代碼如下
function scanKeys(string $pattern, int $count = 100): array
{
$keys = [];
$cursor = 0;
$redis = \support\Redis::connection();
do {
$result = $redis->scan($cursor, ['MATCH' => $pattern, 'COUNT' => $count]);
$cursor = $result[0] ?? 0;
$fetchedKeys = $result[1] ?? [];
$keys = array_merge($keys, $fetchedKeys);
} while ($cursor !== 0);
return array_unique($keys);
}
但改用這個函數(shù)后,keys始終為空...,不知道具體是哪里出了問題,求解答。
function scanKeys(string $pattern, int $count = 100): array
{
$keys = [];
$cursor = 0;
$redis = \support\Redis::connection();
do {
// $result = $redis->scan($cursor, $pattern, $count); // 方法1
$result = $redis->scan($cursor, ['match' => $pattern, 'count' => $count]); // 方法2
$cursor = $result[0] ?? 0;
$fetchedKeys = $result[1] ?? [];
$keys = array_merge($keys, $fetchedKeys);
} while ($cursor !== 0);
return array_unique($keys);
}
兩種方法都試了,結果都一樣,測試代碼如下
$keys = scanKeys('a:*');
dump(['scan', $keys]);
$keys = Redis::keys('a:*');
dump(['keys', $keys]);
打印結果為