gpt4 book ai didi

我可以将 MGET 与 hiredis 一起使用吗?

转载 作者:可可西里 更新时间:2023-11-01 11:23:00 48 4
gpt4 key购买 nike

考虑以下示例:

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

最佳答案

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 会删除整个树。

关于我可以将 MGET 与 hiredis 一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9433095/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com