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 |
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。长期运行的采集进程建议封装成带重连和健康检查的客户端类,而不是在业务代码里散落裸连接。
freeReplyObject 会造成内存持续上涨。