hiredis 是什么

hiredis 是 Redis 官方维护的 C 语言客户端库,提供同步 API,也有异步接口。C++ 工程一般直接用同步 API 封装一层自己的 Redis 工具类。它返回的是通用的 reply 结构,需要按类型解析。

建立连接

#include <hiredis/hiredis.h>

redisContext* c = redisConnect("127.0.0.1", 6379);
if (c == NULL || c->err) {
    if (c) printf("连接错误: %s\n", c->errstr);
    else   printf("分配 context 失败\n");
    return;
}

// 如需密码认证
redisReply* r = (redisReply*)redisCommand(c, "AUTH %s", password);
freeReplyObject(r);

redisContext 是非线程安全的,一个连接不要被多个线程同时使用;多线程场景要么每线程一个连接,要么加锁,要么上连接池。

执行命令并解析回复

redisCommand 返回 redisReply*,用完必须 freeReplyObject。reply 的 type 决定怎么取数据:

redisReply* r = (redisReply*)redisCommand(c, "GET %s", key.c_str());
if (r == NULL) {
    // 连接已断,需要重连
} else if (r->type == REDIS_REPLY_STRING) {
    std::string val = r->str;
} else if (r->type == REDIS_REPLY_NIL) {
    // key 不存在
} else if (r->type == REDIS_REPLY_ERROR) {
    // 服务端返回错误
}
freeReplyObject(r);
reply type含义取值字段
REDIS_REPLY_STRING字符串回复str, len
REDIS_REPLY_ARRAY数组elements, element[]
REDIS_REPLY_INTEGER整数integer
REDIS_REPLY_NIL空(key 不存在)—
REDIS_REPLY_ERROR错误str
REDIS_REPLY_STATUS状态(OK 等)str

Pipeline 批量提交

hiredis 用 redisAppendCommand 先把命令写入输出缓冲,再统一 redisGetReply 取回结果,实现批量提交:

for (int i = 0; i < 100; ++i) {
    redisAppendCommand(c, "SET key:%d %d", i, i);
}
// 逐条取回对应回复
for (int i = 0; i < 100; ++i) {
    redisReply* r = NULL;
    redisGetReply(c, (void**)&r);
    freeReplyObject(r);
}

连接失效与重连

网络抖动、服务端重启都会让连接失效。命令返回空 reply 或 context 标记出错时,要主动释放旧 context 并重新 redisConnect。长期运行的采集进程建议封装成带重连和健康检查的客户端类,而不是在业务代码里散落裸连接。

容易踩的坑