请考虑以下示例:
#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获得多键吗?
Lorem ipsum dolor坐下来。 Lorem ipsum dolor坐着。 Lorem ipsum dolor坐着。 Lorem ipsum dolor坐着。 Lorem ipsum dolor坐着。 Lorem ipsum dolor坐着。 (这是用于愚蠢的代码/文本比率控制。)
答案 0 :(得分:1)
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删除了整个树。