from: http://blog.csdn.net/pla1988/article/details/8510721
源碼:https://github.com/redis/hiredis/blob/master/hiredis.c
/* 作用:用於連接redis服務器 ip : 為redis的ip地址; port: 端口地址; tv:連接超時的參數; */ redisContext *redisConnectWithTimeout(const char *ip, int port, struct timeval tv);
/* 作用:執行命令 c:redisConnectWitTimeout返回的對象; format:命令參數; */ void *redisCommand(redisContext *c, const char *format, ...)
/* 說明:redisCommand返回的對象指針,也就是已經命令返回的結果數據 */ typedef struct redisReply { int type; /* REDIS_REPLY_* */ long long integer; /* The integer when type is REDIS_REPLY_INTEGER */ int len; /* Length of string */ char *str; /* Used for both REDIS_REPLY_ERROR and REDIS_REPLY_STRING */ size_t elements; /* number of elements, for REDIS_REPLY_ARRAY */ struct redisReply **element; /* elements vector for REDIS_REPLY_ARRAY */ } redisReply;
hiRedis操作同步API的接口函數只需下面三個即可:
redisContext*redisConnect(const char *ip, int port);
void*redisCommand(redisContext *c, const char *format, ...);
voidfreeReplyObject(void *reply);
1. 連接(Connecting)
redisconnect函數創建一個redisContext類型的數據結構,用於保存與服務器端的連接狀態。redisContext 結構有一個整數類型的err域,當該值非零時表示連接有錯,並表示錯誤類型。 更多錯誤信息請參考Errors部分。因此,當使用redisconnect函數連接Redis時,需要判斷err域,檢查建立連接是否成功。
redisContext *c = redisConnect("127.0.0.1", 6379);
if (c->err) {
// handle error
2. 發送命令(Send Commands)
hiRedis有多種方式發送命令給Redis。其中,第一個方法是使用redisCommand。該函數的原型與printf很相似。最簡單的形式,我們可以如下使用redisCommand:
reply = redisCommand(context, "SET foo bar");
也可以使用像printf的格式化方法,插入字符串,如下:
reply = redisCommand(context, "SET foo %s", value);
當需要在命令中傳遞一個二進制安全的字符串時,可以使用%b,一個字符串指針,和size_t類型的字符串長度。
reply = redisCommand(context, "SET foo %b", value, valuelen);
3. 使用replies
當命令成功執行時,redisCommand的返回值保存一個reply;而當有錯誤產生時,返回NULL,並且設置context中的err域。當有錯誤產生時,連接不可再用,需要重新創建一個連接。
redisCommand返回的標准的replies為redisReply類型。RedisReply類型的type域用於保存客戶端接收到的是哪鍾類型的reply:
- REDIS_REPLY_STATUS:
命令返回一個status。status 字符串可以使用reply->str訪問,字符串長度使用reply->len訪問
- REDIS_REPLY_ERROR:
命令返回一個error。error字符串訪問同status。
- REDIS_REPLY_INTEGER:
命令返回一個整數。整數值可以使用reply->integer域訪問,類型為long long。
- REDIS_REPLY_NIL
命令返回一個nil對象,表示訪問數據不存在
- REDIS_REPLY_STRING
命令返回一個字符串對象。訪問同status。
- REDIS_REPLY_ARRAY
命令返回一個數組對象。數組元素個數保存在reply->elements,數組中的每個元素都是一個redisReply對象,可以通過reply->element[…index…]訪問。Redis支持嵌套數組。
最后,需要調用freeReplyObject()函數釋放Replies。該函數會自動釋放數組或嵌套數組的sub-replies 對象,因此不需要手動釋放sub-replies。
4. 斷開連接
為了斷開連接和釋放context,需要調用如下函數:
void redisFree(redisContext *c);
該函數會立即關閉socket,然后釋放context創建時的分配內容。