帮我写一份C++读取redis键值对的代码
时间: 2023-08-31 20:26:43 浏览: 68
### 回答1:
好的,以下是读取 Redis 键值对的 C 代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <hiredis/hiredis.h>
int main() {
redisContext *c = redisConnect("127...1", 6379);
if (c == NULL || c->err) {
printf("Error connecting to Redis: %s\n", c == NULL ? "NULL" : c->errstr);
exit(1);
}
redisReply *reply = redisCommand(c, "GET mykey");
if (reply == NULL) {
printf("Error reading key from Redis\n");
exit(1);
}
if (reply->type == REDIS_REPLY_STRING) {
printf("Value of mykey: %s\n", reply->str);
} else {
printf("Unexpected reply type: %d\n", reply->type);
}
freeReplyObject(reply);
redisFree(c);
return ;
}
```
以上代码使用 hiredis 库连接 Redis,读取名为 "mykey" 的键的值,并将其打印到控制台上。如果读取过程中出现错误,程序将会退出并打印错误信息。
### 回答2:
以下是一个简单的C代码示例,用于读取Redis键值对:
#include <stdio.h>
#include <stdlib.h>
#include <hiredis/hiredis.h>
int main(void) {
redisContext *redis = redisConnect("127.0.0.1", 6379); // 连接Redis服务器,默认端口为6379
if (redis == NULL || redis->err) {
fprintf(stderr, "连接Redis失败: %s\n", redis->errstr);
return 1; // 连接失败,返回错误码
}
redisReply *reply = redisCommand(redis, "GET %s", "key"); // 获取键为"key"的值
if (reply == NULL) {
fprintf(stderr, "执行GET命令失败\n");
return 1; // 命令执行失败,返回错误码
}
if (reply->type == REDIS_REPLY_STRING) {
printf("获取到的值为: %s\n", reply->str);
} else {
printf("获取的值不是字符串\n");
}
freeReplyObject(reply); // 释放reply对象
redisFree(redis); // 断开与Redis服务器的连接
return 0; // 程序执行完毕,返回成功码
}
以上代码使用了 hiredis 库来连接和操作 Redis 服务器。首先,我们使用 redisConnect() 函数连接到本地的 Redis 服务器。然后,我们使用 redisCommand() 函数发送 GET 命令来获取键为 "key" 的值。获取到的值保存在 reply 中,我们通过 reply->type 来判断获取到的值的类型,如果是字符串类型,通过 reply->str 来访问其值。最后,我们使用 freeReplyObject() 函数释放 reply 对象,并使用 redisFree() 函数断开与 Redis 服务器的连接。