【问题标题】:access redis hash with hiredis in C在 C 中使用hiredis 访问redis 哈希
【发布时间】:2016-02-11 08:41:05
【问题描述】:

我在 redis 数据库中有两个哈希,名称分别为“hash1”和“hash2”。我在另一个 python 文件中创建了这些哈希。 现在我想用hiredis在.c文件中获取这些哈希中的所有键和值。 那可能吗?我只看到了一些示例,您现在应该输入键的名称以便获取它们的值,但我想根据哈希的名称获取所有键和值。基本上我想要这个命令 redis_cache.hgetall(HASH_NAME) 但是有hiredis。

谢谢

【问题讨论】:

    标签: python c hash redis hiredis


    【解决方案1】:

    一个 redisReply 是一个类型化的对象(见 type 字段),一个多批量回复有一个特定的类型(REDIS_REPLY_ARRAY)。查看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.
    

    HGETALL 将它们的键值作为列表返回,每个值都可以在每个键之后找到:

    redisReply *reply = redisCommand(redis, "HGETALL %s", "foo");
    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 = i + 2 ) {
        printf( "Result: %s = %s \n", reply->element[i]->str, reply->element[i + 1]->str );
      }
    }
    freeReplyObject(reply);
    

    【讨论】:

    • 所以“foo”是哈希的名称,而不是redis数据库中存在的键?
    • 是的,redis.io/commands/hgetall - 此命令只有一个参数 - 哈希名称。
    • 并且返回的数组将包含索引 i、i+1 -- i+2、i+3 等中的键和值?
    • 是的,i 作为第一个键,i + 1 作为第一个值,依此类推。
    猜你喜欢
    • 2012-07-02
    • 2014-05-06
    • 1970-01-01
    • 2013-07-27
    • 2016-10-04
    • 1970-01-01
    • 2021-07-01
    • 2012-05-08
    • 2018-02-09
    相关资源
    最近更新 更多