C++中如何使用Hiredis库连接Redis服务器

c++
792
2024/8/22 18:31:30
栏目: 云计算
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中使用Hiredis库连接Redis服务器的步骤如下:

  1. 首先,需要在项目中包含Hiredis库的头文件。你可以从Hiredis的GitHub仓库中下载最新版本的Hiredis并将其包含在项目中:
#include <hiredis/hiredis.h>
  1. 创建一个Redis连接对象,并连接到Redis服务器:
redisContext *context = redisConnect("127.0.0.1", 6379);
if (context == NULL || context->err) {
    if (context) {
        printf("Error: %s\n", context->errstr);
        redisFree(context);
    } else {
        printf("Cannot allocate redis context\n");
    }
    return -1;
}

这里将连接到本地Redis服务器,如果连接失败,会输出错误信息并返回-1。

  1. 执行Redis命令:
redisReply *reply = (redisReply *)redisCommand(context, "SET key value");
if (reply == NULL) {
    printf("Error executing command\n");
    return -1;
}
printf("Command executed successfully\n");

freeReplyObject(reply);

这里执行了一个SET操作,将key设置为value。

  1. 关闭连接并释放资源:
redisFree(context);

这样就完成了通过Hiredis库连接到Redis服务器并执行命令的过程。在实际使用中,你可以根据需要执行其他操作,如GET、DEL等。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++中clock函数报错怎么解决