php中使用redis HyperLogLogs

问题

前些日子学习了reids的HyperLogLogs(不熟悉此功能的同学可参看这里),想用php试试。我在php中用的redis扩展是phpredis,查了一下api,居然没有HyperLogLogs相关的api(pfadd, pfcount等) -_-|||

曙光

总不至于自己按reids协议用原生socket写吧…详细查了下文档,发现了这个api–rawCommand,可以让你直接使用原生redis命令。比如:

/* Returns: true */
$redis->rawCommand("set", "foo", "bar"); 

/* Returns: "bar" */
$redis->rawCommand("get", "foo");

看来可以考虑尝试用此api直接执行pfadd, pfcount。

又一个问题

写了下面的代码(hyper.php),模拟统计ip个数的case, 预期输出是3。

$redis = new Redis();
$res = $redis->connect('127.0.0.1', '6379');

$ipList = array(
    '10.1.1.1',
    '10.1.1.2',
    '10.1.1.2',
    '10.1.1.3',
);

foreach ($ipList as $ip){
    $redis->rawCommand('pfadd', 'ips', $ip);
}

$result = $redis->rawCommand('pfcount', 'ips');

echo $result, "\n";

执行代码,居然告诉我无此方法,又一道黑线划过!

PHP Fatal error:  Call to undefined method Redis::rawCommand()

解决

查了下,原来phpredis是在2.2.7及以上版本才支持rawCommand, 详见Release notes。

那么我目前使用的phpredis版本是多少呢?

$ext = new ReflectionExtension('redis');
echo $ext->getVersion();

结果是2.2.4,难怪不支持。

下载了phpreis 2.2.7(点我下载),编译安装。
再次执行hyper.php,顺利得到结果3!

总结

php中使用HyperLogLogs需要
1. redis(server端) 2.8.9及以上版本
2. phpredis版本2.2.7及以上
3. 使用rawCommand执行HyperLogLogs相关api

你可能感兴趣的:(nosql)