wget https://download.redis.io/releases/redis-3.0.6.tar.gz
tar xzf redis-3.0.6.tar.gz
cd redis-3.0.6
make
# 啟動服務端
src/redis-server
# 新終端啟動客戶端測試
src/redis-cli
# 測試
127.0.0.1:6379> set foo bar
OK
127.0.0.1:6379> get foo
"bar"
wget https://github.com/redis/hiredis/archive/master.zip
unzip master.zip
cd hiredis-master
make
sudo make install
# 安裝路徑:
# /usr/local/include/hiredis/ 頭文件
# /usr/local/lib/libhiredis.so 動態庫
# /usr/local/lib/pkgconfig/hiredis.pc pkg-config 支持
| 函數 | 用途 | 關鍵參數/返回 |
|---|---|---|
redisConnect(ip, port) | 建立連接 | 返回 redisContext*,NULL 表失敗;ctx->err 非 0 表錯誤 |
redisCommand(ctx, fmt, ...) | 發送命令 | printf 風格格式化;返回 redisReply*,NULL 表失敗 |
freeReplyObject(reply) | 釋放回覆對象 | 必須調用,否則洩漏 |
redisFree(ctx) | 關閉連接釋放上下文 | 程序結束前調用 |
// 連接上下文
typedef struct redisContext {
int err; char errstr[128];
int fd; int flags;
char *obuf;
redisReader *reader;
// ... tcp/unix_sock 信息
} redisContext;
// 命令回覆
typedef struct redisReply {
int type; // REDIS_REPLY_* 類型
long long integer; // 整數回覆
int len; char *str; // 字符串/錯誤/狀態回覆
size_t elements; // 數組元素數
struct redisReply **element; // 數組元素指針陣列
} redisReply;
#define REDIS_REPLY_STRING 1
#define REDIS_REPLY_ARRAY 2
#define REDIS_REPLY_INTEGER 3
#define REDIS_REPLY_NIL 4
#define REDIS_REPLY_STATUS 5
#define REDIS_REPLY_ERROR 6
#include <stdio.h> #include <stdlib.h> #include <hiredis/hiredis.h>
int main() {
redisContext *ctx = redisConnect("127.0.0.1", 6379);
if (!ctx || ctx->err) {
fprintf(stderr, "Connect error: %s\n", ctx ? ctx->errstr : "NULL context");
if (ctx) redisFree(ctx);
return EXIT_FAILURE;
}
redisReply *reply = redisCommand(ctx, "GET foo");
if (reply && reply->type == REDIS_REPLY_STRING)
printf("GET foo => %s\n", reply->str);
else
printf("Reply type: %d\n", reply ? reply->type : -1);
freeReplyObject(reply);
redisFree(ctx);
return 0;
}
編譯:gcc -Wall -ggdb -o simpleget simpleget.c -lhiredis

#include <signal.h> // 忽略 SIGPIPE 防止連接斷開導致進程退出
signal(SIGPIPE, SIG_IGN);
redisContext *ctx = redisConnect("127.0.0.1", 6379);
// ... 錯誤檢查同上 ...
freeReplyObject(redisCommand(ctx, "LPUSH mylist foo"));
freeReplyObject(redisCommand(ctx, "LPUSH mylist bar"));
redisReply *reply = redisCommand(ctx, "LRANGE mylist 0 -1");
if (reply && reply->type == REDIS_REPLY_ARRAY && reply->elements == 2) {
printf("%s %s\n", reply->element[0]->str, reply->element[1]->str);
} else {
printf("LRANGE error: type=%d\n", reply ? reply->type : -1);
}
freeReplyObject(reply);
redisFree(ctx);

#include <hiredis/hiredis.h>-lhiredis(需 sudo ldconfig 刷新庫緩存)find /usr/local/include -name "*.h" | xargs grep REDIS_REPLY_STRINGredisAsyncContext、redisAsyncCommand)