考虑以下示例:
#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得到多个密钥吗?
洛勒姆·伊普苏姆·多洛坐在阿梅特。洛勒姆·伊普苏姆·多洛坐在阿梅特。洛勒姆·伊普苏姆·多洛坐在阿梅特。洛勒姆·伊普苏姆·多洛坐在阿梅特。洛勒姆·伊普苏姆·多洛坐在阿梅特。洛勒姆·伊普苏姆·多洛坐在阿梅特。(用于愚蠢的代码/文本比率控制。)
最佳答案
redis reply是一个类型化的对象(请参见type字段),而多批量回复有一个特定的类型(redis_reply_数组)。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会删除整个树。
关于c - 我可以将MGET与hiredis一起使用吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9433095/