Phpredis自动键前缀,KEYS / SCAN和TTL命令组合异常行为

时间:2018-07-13 09:35:56

标签: php redis prefix ttl phpredis

在phpredis中使用自动键前缀时,例如

$redis->setOption(Redis::OPT_PREFIX, 'dev:');

KEYS SCAN 命令的结果结合使用时, TTL 命令的行为与预期不符。

我猜对行为的最好解释是下面的代码片段:

<?php

$redis = new Redis();
$redis->connect('127.0.0.1', 6379, 5);
$redis->setOption(Redis::OPT_PREFIX, 'dev:');

$redis->set('foo', 'bar'); // Will actually set key "dev:foo" with value "bar"

$keyPattern = '*';
$iterator = null;
$keys = [];

// Get all keys stored in Redis using SCAN
while (false !== ($result = $redis->scan($iterator, $keyPattern)))
{
  foreach ($result as $key)
  {
    if (!in_array($key, $keys))
    {
      $keys[] = $key;
    }
  }
}

// Getting TTL-s
foreach ($keys as $key)
{
  // This will actually now look for "dev:dev:foo" key TTL not "dev:foo"
  // because prefix "dev:" is added automatically. Is this bug or feature?
  echo $redis->ttl($key); 
  // will echo -2 because "dev:dev:foo" does not exist
}

这是错误或功能吗?

0 个答案:

没有答案