【问题标题】:Can I use MGET with hiredis?我可以将 MGET 与hiredis 一起使用吗?
【发布时间】:2012-02-24 15:14:31
【问题描述】:

考虑以下示例:

#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获取多键吗?

【问题讨论】:

    标签: c redis hiredis


    【解决方案1】:

    一个 redisReply 是一个类型化的对象(见 type 字段),一个多批量回复有一个特定的类型(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 会删除整个树。

    【讨论】:

    • @Didier Spezia HGETALL 怎么样?键和值都将作为 element[i] 出现对吗?
    • 否 - 我认为 key 将作为 element[i] 而 value 作为 element[i+1]
    猜你喜欢
    • 2023-03-25
    • 2020-08-04
    • 2018-10-23
    • 2011-02-22
    • 2021-03-16
    • 2016-11-20
    • 2019-01-25
    • 2011-06-11
    • 2017-02-20
    相关资源
    最近更新 更多