我可以将 MGET 与 hiredis 一起使用吗?

标签 c redis hiredis

考虑以下示例:

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <hiredis/hiredis.h>

int main(int argc, char **argv) {
  redisContext *redis;
  redisReply *reply;

  redis = redisConnect("127.0.0.1", 6379);
  if(redis->err) {
    fprintf(stderr, "Connection error: %s\n", redis->errstr);
    exit(EXIT_FAILURE);
  }

  reply = redisCommand(redis, "SET %s %s", "foo", "bar");
  printf("SET %s %s: %s\n", "foo", "bar", reply->str);
  freeReplyObject(reply);

  reply = redisCommand(redis, "SET %s %s", "name", "value");
  printf("SET %s %s: %s\n", "name", "value", reply->str);
  freeReplyObject(reply);

  reply = redisCommand(redis, "MGET %s %s", "foo", "name");
  printf("MGET %s %s: %s\n", "foo", "name", reply->str);
  freeReplyObject(reply);

  exit(EXIT_SUCCESS);
}

输出是:

PING: PONG
SET foo bar: OK
GET foo: bar
SET name value: OK
MGET foo name: (null)

这是关于从 MGET 返回的。我可以使用 hiredis 获取多个 key 吗?

最佳答案

redisReply 是一个类型对象(参见类型字段),并且多批量回复具有特定类型 (REDIS_REPLY_ARRAY)。在这种情况下,str 字段不相关。

来自 hiredis 文档:

The number of elements in the multi bulk reply is stored in reply->elements.
Every element in the multi bulk reply is a redisReply object as well
and can be accessed via reply->element[..index..].
Redis may reply with nested arrays but this is fully supported.

所以你的代码应该修改如下:

reply = redisCommand(redis, "MGET %s %s", "foo", "name" );
if ( reply->type == REDIS_REPLY_ERROR )
  printf( "Error: %s\n", reply->str );
else if ( reply->type != REDIS_REPLY_ARRAY )
  printf( "Unexpected type: %d\n", reply->type );
else 
{
  int i;
  for ( i=0; i<reply->elements; ++i )
    printf( "Result: %s\n", reply->element[i]->str );
}
freeReplyObject(reply);

有了这个改变,现在的输出是:

SET foo bar: OK
SET name value: OK
Result: bar
Result: value

注意:不需要释放每个单独的元素,因为 freeReplyObject 会删除整个树。

关于我可以将 MGET 与 hiredis 一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9433095/

相关文章:

c++ - C 和 C++ : Difference between Casting and Conversion

python - 在Python中将参数传递给dll的函数会导致访问冲突写入0x00000014

c - 是什么让 D 成为一门好语言?

php - 如何同步 PHP 和 NodeJS 与 Redis 并按顺序获取数据

c - 给学生打分

bash - 删除Redis中的很多键

我们可以通过 hiredis 将 C int 数组设置为 Redis 中的键值吗?

Redis数据库存储限制和HA

node.js - 没有使用这个基本的 socket.io + redis 设置接收事件?