1、linux下如何安裝hiredis
1)下載地址
https://github.com/redis/hiredis
2)編譯和安裝
解壓後的檔案夾執行 make;make install;
3)標頭檔包含
include <hiredis/hiredis.h>
4)編譯選項
makefile檔案中加入 LDFLAGS = -lhiredis
2、主要結構
主要關注2個結構體,
1)redisContext
//對應與redis的串連
/* Context for a connection to Redis */typedef struct redisContext { int err; /* Error flags, 0 when there is no error */ char errstr[128]; /* String representation of error when applicable */ int fd; int flags; char *obuf; /* Write buffer */ redisReader *reader; /* Protocol reader */ enum redisConnectionType connection_type; struct timeval *timeout; struct { char *host; char *source_addr; int port; } tcp; struct { char *path; } unix_sock;} redisContext;
2)redisReply
//對應redis命令的回複結果
/* This is the reply object returned by 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;
2、主要介面
主要有4個介面,
1)redisContext* redisConnect(const char *ip, int port)
//串連redis。
2)void *redisCommand(redisContext *c, const char *format, ...);
//執行redis操作命令
3)void freeReplyObject(void *reply);
//釋放執行redis操作命令回複的記憶體
4)void redisFree(redisContext *c);
//釋放串連上下文。 3、異常處理
主要4種異常情況會出現,
1)獲得的redisContext指標為null
異常處理辦法:再次嘗試與redis建立新的串連上下文。
2)獲得的redisContext指標err不為0
異常處理辦法:再次嘗試與redis建立新的串連上下文。
3)獲得的redisReply指標為null
異常處理辦法:斷開redis串連再次與redis建立串連並嘗試執行命令。
4)獲得的reply指標的type不是期望的類型,
異常處理辦法:斷開redis串連再次與redis建立串連並嘗試執行命令。
至此hiredis瞭解完畢,接下來就可以在其他模組中調用了。