我正在使用 PHP-Redis 和 Redis 版本 3.1.6
$result = $redis->keys('source_1234_[a-zA-Z]*_[0-9]*');
产生
{array} [6]
0 = "source_1234_test_1"
1 = "source_1234_test_2"
2 = "source_1234_test_3"
3 = "source_1234_test_4"
4 = "source_1234_test_5"
5 = "source_1234_test_6"
不过
$iterator = 0;
$result = $redis->scan($iterator, 'source_1234_[a-zA-Z]*_[0-9]*');
返回
FALSE
我正在阅读 KEYS 的文档和 SCAN但它所说的一切都支持 glob-style 模式。
所以检查http://www.globtester.com/我可以确认该模式有效并且应该返回正确的结果。为什么会有差异,为什么在这种情况下 SCAN 会返回 FALSE?
最佳答案
您的代码有两个问题:
(a) 您需要将迭代器设置为 NULL
,而不是 0
。
0
从对 SCAN
的调用中返回,表示已扫描所有键。因此它将停止并返回 false
。
(b) SCAN
遍历所有键的集合,为每次调用返回每个集合的匹配项。您只调用扫描一次。它将扫描第一个 COUNT
个键,如果没有匹配的键则返回 false。
参见 https://redis.io/commands/scan#number-of-elements-returned-at-every-scan-call :
SCAN family functions do not guarantee that the number of elements returned per call are in a given range. The commands are also allowed to return zero elements, and the client should not consider the iteration complete as long as the returned cursor is not zero.[...]
要获得与 KEYS
相同的结果,您需要遍历所有键集:
$iterator = NULL
while($iterator != 0) {
$arr_keys = $redis->scan($iterator, 'source_1234_[a-zA-Z]*_[0-9]*')
foreach($arr_keys as $str_key) {
echo $str_key;
}
}
关于Redis (PHP-Redis) SCAN 和 KEYS 显示相同模式的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49670484/