Redis (PHP-Redis) SCAN 和 KEYS 显示相同模式的不同结果

标签 redis glob phpredis

我正在使用 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/

相关文章:

spring-security - session 范围内的 Spring session + Redis + Infinispan 缓存失败

linux - 如果存在多个目录,则移动目录 - 测试 globbing 模式是否匹配任何内容

amazon-web-services - redis.so 模块未加载

php - Laravel Redis 作业未排队

laravel - 如何使用 Redis TLS 配置 Laravel 5.7(使用 phpredis)

java - jar在catalina主页的lib文件夹中时,context.xml中类的ClassNotFoundException

spring - grails 2.3.5 + redis-gorm 插件 + spring security 核心插件

带有 TTL 的 Redis 多集

ruby-on-rails - Ruby Dir ['**/*' ] 限制?

python - 在PYTHON中将多个文件读入单独的数据帧