2012-02-24 55 views
0

考慮下面的例子:可以使用MGET與僱用?

#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回報。 1可以得到許多按鍵採用聘請?

Lorem存有胡蘿蔔。 Lorem存有胡蘿蔔。 Lorem存有胡蘿蔔。 Lorem存有胡蘿蔔。 Lorem存有胡蘿蔔。 Lorem存有胡蘿蔔。 (它是愚蠢的代碼/文字的系統控制。)

回答

1

甲redisReply是一個類型的對象(見類型字段),以及多塊體答覆具有特定的類型(REDIS_REPLY_ARRAY)。 STR的領域是不是在這種情況下,相關的。

從聘請文檔:

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刪除整個樹。

+0

感謝凱瑟琳,1整最好開始閱讀說明書。 – 2012-02-27 01:09:08

+0

@Didier拉斯佩齊亞什麼HGETALL?鍵和值都將來作爲 元素[I]吧?沒有 – 2012-11-28 09:48:49

+0

- 1認爲主要會爲元素[i]和值元素[I + 1] – 2012-11-28 11:03:39