菜单 学习猿地 - LMONKEY

项目中使用Redis的游标scan的一些小问题

liangxiaowxylk profile image liangxiaowxylk ・1 min read

      最近项目中有一个需求就是在下拉中要筛选车辆列表,本来想着是在内存中全部用程序去遍历处理,但发现数据有点多,一个个去处理会有点慢。然后就找到了redis的游标

感觉这个能满足我的需求,我可以把key存成车牌号,value为车辆id的值,通过正则匹配到车牌号就能获取车辆id来查找信息了。思路有了,接下来就开工了。

    在官网上找到这么一段程序

 

/* Without enabling Redis::SCAN_RETRY (default condition) */
$it = NULL;
do {
    // Scan for some keys
    $arr_keys = $redis->scan($it);

    // Redis may return empty results, so protect against that
    if ($arr_keys !== FALSE) {
        foreach($arr_keys as $str_key) {
            echo "Here is a key: $str_key\n";
        }
    }
} while ($it > 0);
echo "No more keys to scan!\n";

/* With Redis::SCAN_RETRY enabled */
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
$it = NULL;

/* phpredis will retry the SCAN command if empty results are returned from the
   server, so no empty results check is required. */
while ($arr_keys = $redis->scan($it)) {
    foreach ($arr_keys as $str_key) {
        echo "Here is a key: $str_key\n";
    }
}
echo "No more keys to scan!\n";

这段程序在我的环境会有问题(php7). 会报  Parameter 1 to Redis::scan() expected to be a reference, value given

应该是那个游标对象$it得用引用。所以需要改成call_user_func_array调用

 

$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
$it = NULL;

/* phpredis will retry the SCAN command if empty results are returned from the
   server, so no empty results check is required. */
while ($array = call_user_func_array(array($redis, 'scan'), array(&$it)) {
    foreach ($arr_keys as $str_key) {
        echo "Here is a key: $str_key\n";
    }
}
echo "No more keys to scan!\n";

用上面的程序,就能通过游标把所有符合的值取出来。在业务层使用就行了

评论 (0)