赞
踩
使用redis扩展的scan函数,发现这个函数写的很有问题,返回值并没有游标,而且游标初始值要设置为null而不是0,感觉用起来还是挺别捏的,直接放弃了,直接使用万能的rawCommand函数来执行原生的redis命令。
可参考:https://blog.csdn.net/raoxiaoya/article/details/100515541
SCAN 命令用于迭代当前数据库中的数据库键
。
HSCAN 命令用于迭代哈希键中的键值对
。
1、scan 命令
比如,总共有9个key,两次调用 scan 命令返回值类似于
array:2 [ 0 => "33" 1 => array:4 [ 0 => "read3:departRank:7_660_avg" 1 => "read3:departRank:7_662_user" 2 => "read3:departRank:7_660_sum" 3 => "read3:departRank:7_0_avg" ] ] array:2 [ 0 => "0" 1 => array:5 [ 0 => "read3:departRank:7_5_user" 1 => "read3:departRank:7_660_user" 2 => "read3:departRank:7_5_sum" 3 => "read3:departRank:7_5_avg" 4 => "read3:departRank:7_0_sum" ] ]
封装函数,整理数据,最终返回key的数组。
public static function scanGetKeys($pattern, $count = 50){ $ret = []; $iterator = 0; while (true) { $result = Redis::rawCommand("scan", $iterator, 'match', $pattern, 'count', $count); dump($result); if ($result === false) { break; } $ret = array_merge($ret, $result[1]); $iterator = $result[0]; if($result[0] == 0){ break; } } return $ret; }
调用 $r1 = Read3Service::scanGetKeys('getReadtimeUserRank:*');
2、hscan 命令
如果你的hash表的key较多,那么也需要使用hscan命令,hscan 命令返回值类似于
array(2) {
[0]=>
string(1) "0"
[1]=>
array(4) {
[0]=>
string(1) "5"
[1]=>
string(1) "3"
[2]=>
string(1) "2"
[3]=>
string(1) "4"
}
}
对应的是
封装函数,整理数据,最终返回 key => value 的数组。
public static function hscanGetKeyValue($key, $pattern, $count = 50) { $ret = []; $iterator = 0; while (true) { $result = Redis::rawCommand("hscan", $key, $iterator, 'match', $pattern, 'count', $count); if ($result === false) { break; } $temp = $result[1]; foreach($temp as $k => $v){ if($k % 2 == 0){ $ret[$v] = ''; // $k偶数为key }else{ $ret[$temp[$k-1]] = $v; // $k奇数为value } } $iterator = $result[0]; if($result[0] == 0){ break; } } return $ret; }
hscanGetKeyValue函数返回的是整理后的key => value 对。
调用 $list = RedisService::hscanGetKeyValue($key, '*');
array(2) {
[5]=>
string(1) "3"
[2]=>
string(1) "4"
}
3、zscan 命令
public static function zscanGetKeyValue($key, $pattern, $count = 50) { $ret = []; $iterator = 0; while (true) { $result = Redis::rawCommand("zscan", $key, $iterator, 'match', $pattern, 'count', $count); if ($result === false) { break; } $temp = $result[1]; foreach($temp as $k => $v){ if($k % 2 == 0){ $ret[$v] = ''; // $k偶数为key }else{ $ret[$temp[$k-1]] = $v; // $k奇数为value } } $iterator = $result[0]; if($result[0] == 0){ break; } } return $ret; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。