C++如何操作Redis数据库_使用hiredis库在C++中与Redis进行交互

使用hiredis库可在C++中高效操作Redis。首先安装hiredis,Ubuntu/Debian执行sudo apt-get install libhiredis-dev,CentOS/RHEL执行sudo yum install hiredis-devel,或从GitHub源码编译安装。接着编写C++程序,包含头文件,使用redisConnect连接Redis服务器,redisCommand发送命令,如SET和GET,通过检查redisReply的type字段处理不同回复类型,如REDIS_REPLY_STRING、REDIS_REPLY_STATUS等,操作完成后调用freeReplyObject释放内存,最后用redisFree关闭连接。可将常用操作封装成C++类提高复用性,如定义RedisClient类封装连接、SET、GET方法。编译时需链接hiredis库:g++ redis_test.cpp -lhiredis -o redis_test。注意事项包括确保Redis服务运行、及时释放内存、生产环境添加超时与重试机制,适合高性能、嵌入式场景。

要在C++中操作Redis数据库,最常用的方式是使用 hiredis —— Redis官方推荐的C语言客户端库。由于C++兼容C,可以直接使用 hiredis 并封装成更易用的C++接口。下面介绍如何在C++项目中集成和使用 hiredis 与 Redis 进行交互。

1. 安装 hiredis 库

首先需要在系统中安装 hiredis。可以通过源码编译或包管理器安装。

Ubuntu/Debian:

sudo apt-get update
sudo apt-get install libhiredis-dev

CentOS/RHEL:

sudo yum install hiredis-devel

从源码安装:

git clone https://github.com/redis/hiredis.git
cd hiredis
make
sudo make install
sudo ldconfig  # 刷新共享库缓存

2. 编写 C++ 程序连接 Redis

使用 hiredis 的基本流程包括:建立连接、发送命令、获取回复、断开连接。

以下是一个简单的 C++ 示例,演示如何连接 Redis 并执行 SET 和 GET 操作:

#include 
#include 
#include 

int main() { // 建立同步连接 redisContext *ctx = redisConnect("127.0.0.1", 6379); if (ctx == nullptr || ctx->err) { if (ctx) { std::cerr << "Connection error: " << ctx->errstr << std::endl; } else { std::cerr << "Context creation failed" << std::endl; } return 1; }

// 执行 SET 命令
redisReply *reply = (redisReply*)redisCommand(ctx, "SET %s %s", "name", "Tom");
if (reply && reply->type == REDIS_REPLY_STATUS && (std::string(reply->str) == "OK")) {
    std::cout << "SET successful" << std::endl;
} else {
    std::cerr << "SET failed" << std::endl;
}
freeReplyObject(reply);

// 执行 GET 命令
reply = (redisReply*)redisCommand(ctx, "GET %s", "name");
if (reply && reply->type == REDIS_REPLY_STRING) {
    std::cout << "GET name = " << reply->str << std::endl;
} else {
    std::cerr << "GET failed or key not found" << std::endl;
}
freeReplyObject(reply);

// 关闭连接
redisFree(ctx);
return 0;

}

3. 编译与链接 hiredis

编译时需链接 hiredis 库。假设源文件名为 redis_test.cpp,使用如下命令编译:

g++ redis_test.cpp -lhiredis -o redis_test

运行程序:

./redis_test

输出应为:

SET successful
GET name = Tom

4. 处理不同类型的 Redis 回复

Redis 命令返回的回复类型多样,redisReply 结构体中的 type 字段表示类型,常见值包括:

  • REDIS_REPLY_STRING:字符串回复(如 GET)
  • REDIS_REPLY_ARRAY:数组回复(如 LRANGE, KEYS)
  • REDIS_REPLY_INTEGER:整数回复(如 INCR)
  • REDIS_REPLY_STATUS:状态回复(如 SET 返回 OK)
  • REDIS_REPLY_NIL:空结果(如 GET 不存在的键)
  • REDIS_REPLY_ERROR:错误信息

示例:遍历列表(LIST)类型数据:

reply = (redisReply*)redisCommand(ctx, "LRANGE %s 0 -1", "mylist");
if (reply && reply->type == REDIS_REPLY_ARRAY) {
    for (size_t i = 0; i < reply->elements; ++i) {
        std::cout << "Item " << i << ": " << reply->element[i]->str << std::endl;
    }
}
freeReplyObject(reply);

5. 封装成 C++ 类(可选进阶)

为了提升代码可读性和复用性,可以将 hiredis 封装成一个简单的 C++ 类:

#include 
#include 

class RedisClient { private: redisContext *context;

public: RedisClient(const std::string& host, int port) { context = redisConnect(host.c_str(), port); if (!context || context->err) { if (context) std::cerr << "Error: " << context->errstr << std::endl; context = nullptr; } }

~RedisClient() {
    if (context) redisFree(context);
}

bool set(const std::string& key, const std::string& value) {
    redisReply *reply = (redisReply*)redisCommand(context, "SET %s %s", key.c_str(), value.c_str());
    bool ok = reply && reply->str && std::string(reply->str) == "OK";
    freeReplyObject(reply);
    return ok;
}

std::string get(const std::string& key) {
    redisReply *reply = (redisReply*)redisCommand(context, "GET %s", key.c_str());
    std::string result;
    if (reply && reply->type == REDIS_REPLY_STRING) {
        result = reply->str;
    }
    freeReplyObject(reply);
    return result;
}

};

使用方式:

RedisClient redis("127.0.0.1", 6379);
redis.set("city", "Beijing");
std::cout << "city = " << redis.get("city") << std::endl;

注意事项

  • 每次 redisCommand 调用后必须调用 freeReplyObject 防止内存泄漏
  • 确保 Redis 服务正在运行(默认端口 6379)
  • 同步 API(hiredis 同步接口)适用于大多数场景,若需异步通信可使用 hiredis 的异步模式 + event loop(如 ae 或 libev)
  • 生产环境中建议增加超时连接和重试机制

基本上就这些。使用 hiredis 在 C++ 中操作 Redis 简单高效,适合嵌入式、高性能服务等场景。