Hiredis 是輕量級 Redis C 客戶端,本文系統講解上下文管理、命令執行、回覆解析、連接池、發布訂閱模式完整流程。
// 連接上下文
typedef struct redisContext {
int err; // 錯誤碼
char errstr[128]; // 錯誤信息
int fd; // 套接字
int flags;
char *obuf; // 輸出緩衝區
redisReader *reader; // 協議解析器
// 連接參數...
} redisContext;
// 回覆對象
typedef struct redisReply {
int type; // 類型
long long integer; // 整數值
int len; // 字符串長度
char *str; // 字符串/錯誤/狀態
size_t elements; // 數組元素數
struct redisReply **element; // 數組元素指針
} redisReply;
| 常量 | 值 | 含義 | 數據字段 |
|---|---|---|---|
| REDIS_REPLY_STRING | 1 | 字符串 | str, len |
| REDIS_REPLY_ARRAY | 2 | 數組 | element, elements |
| REDIS_REPLY_INTEGER | 3 | 整數 | integer |
| REDIS_REPLY_NIL | 4 | 空值 | - |
| REDIS_REPLY_STATUS | 5 | 狀態(OK等) | str, len |
| REDIS_REPLY_ERROR | 6 | 錯誤 | str, len |
redisConnect(ip, port) → 檢查 ctx->errredisCommand(ctx, fmt, ...) → 返回 redisReply*reply->type 分支處理freeReplyObject(reply) (必須調用)redisFree(ctx)
// 格式化命令 (支援 %b 二進制)
redisCommand(ctx, "SET %s %b", key, val, len);
// 數組參數命令 (二進制安全)
redisCommandArgv(ctx, argc, argv, argvlen);
// Pipeline 批量發送
redisAppendCommand(ctx, "GET key1");
redisAppendCommand(ctx, "GET key2");
redisGetReply(ctx, &reply1);
redisGetReply(ctx, &reply2);
| 常量 | 值 | 含義 |
|---|---|---|
| REDIS_ERR_IO | 1 | 讀寫錯誤 |
| REDIS_ERR_EOF | 3 | 連接關閉 |
| REDIS_ERR_PROTOCOL | 4 | 協議解析錯誤 |
| REDIS_ERR_OOM | 5 | 內存不足 |
| REDIS_ERR_OTHER | 2 | 其他錯誤 |
redisContext *ctx = redisConnect("127.0.0.1", 6379);
redisReply *reply = redisCommand(ctx, "SUBSCRIBE channel");
freeReplyObject(reply); // 訂閱確認回覆
while (redisGetReply(ctx, (void**)&reply) == REDIS_OK) {
if (reply->type == REDIS_REPLY_ARRAY && reply->elements == 3) {
redisReply *msg = reply->element[2]; // [subscribe, channel, message]
printf("收到消息: %s\n", msg->str);
}
freeReplyObject(reply);
}
redisFree(ctx);
redisConnectWithTimeoutfreeReplyObject異步模式基於 redisAsyncContext,需事件循環支援,適合高併發場景,此處不展開。
掌握 Hiredis 核心 API,是 C/C++ 系統接入 Redis 的必經之路。