使用 hiredis 同步连接 Redis 需调用 redisConnectWithTimeout 设置超时(单位为 struct timeval),连接后必须检查 context->err;执行命令需按 redisReply->type 分支安全处理并调用 freeReplyObject 释放;二进制数据须用 redisCommandArgv;context 非线程安全且无自动重连,需手动管理连接与 reply 生命周期。

怎么用 hiredis 连 redis 服务(同步模式)
hiredis 默认是同步阻塞的,连接失败或网络卡住会直接 hang 住线程。所以第一步必须设好超时,否则生产环境容易出问题。
-
redisConnect不支持超时,得用redisConnectWithTimeout - 超时单位是
Struct timeval,不是毫秒——{1, 500000}表示 1.5 秒 - 连接后务必检查
context->err,不能只看指针是否为空(比如认证失败时指针非空但err非零)
struct timeval timeout = {1, 500000}; redisContext *c = redisConnectWithTimeout("127.0.0.1", 6379, timeout); if (c == nullptr || c->err) { if (c) { fprintf(stderr, "Redis connection error: %sn", c->errstr); redisFree(c); } return -1; }
怎么执行 SET/GET 命令并安全取返回值
hiredis 的 redisCommand 返回的是 redisReply*,但它的结构不是扁平的,类型判断和字段访问必须严格按 reply->type 分支处理,否则容易段错误或读错内存。
-
REDIS_REPLY_STRING才有str和len;REDIS_REPLY_Integer要用integer字段 -
REDIS_REPLY_NIL表示 key 不存在,此时str == nullptr,不能直接strlen - 所有
redisReply*必须用freeReplyObject释放,不释放会内存泄漏
redisReply *reply = (redisReply*)redisCommand(c, "SET mykey 'hello'"); if (reply && reply->type == REDIS_REPLY_STATUS && strcmp(reply->str, "OK") == 0) { printf("SET successn"); } freeReplyObject(reply); reply = (redisReply*)redisCommand(c, "GET mykey"); if (reply) { if (reply->type == REDIS_REPLY_STRING) { printf("GET result: %.*sn", (int)reply->len, reply->str); } else if (reply->type == REDIS_REPLY_NIL) { printf("key not existsn"); } } freeReplyObject(reply);
怎么处理批量命令和二进制安全数据
Redis 原生支持二进制 key/value,但 C 字符串习惯用