hiredis 是redis的客戶端sdk,可以讓程序操作redis。本文先講建立連接,基本的get/set命令,讀寫二進制,獲取多個結果來講。假設讀者已經了解redis命令了。
hiredis的代碼也包含在redis代碼中,redis\deps\hiredis目錄下,接口很簡單,幾乎不用封裝就可以用。
1 連接redis數據庫
1.1 無超時時間,阻塞
redisContext *redisConnect(const char *ip, int port);
1.2 設置超時時間,阻塞
redisContext *redisConnectWithTimeout(const char *ip, int port, const struct timeval tv);
1.3 非阻塞,立刻返回,也就無所謂超時
redisContext *redisConnectNonBlock(const char *ip, int port);
2 執行命令
void *redisCommand(redisContext *c, const char *format, ...);
2.1 返回值
返回值是redisReply類型的指針:
/* This is the reply object returned by redisCommand() */ typedef struct redisReply { int type; /* REDIS_REPLY_* */ PORT_LONGLONG 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.2 返回值類型
type字段,包含以下幾種類型:
#define REDIS_REPLY_STRING 1 //字符串 #define REDIS_REPLY_ARRAY 2 //數組,例如mget返回值 #define REDIS_REPLY_INTEGER 3 //數字類型 #define REDIS_REPLY_NIL 4 //空 #define REDIS_REPLY_STATUS 5 //狀態,例如set成功返回的‘OK’ #define REDIS_REPLY_ERROR 6 //執行失敗
3 基本命令,get,set
3.1 set
redisReply *r1 = (redisReply*)redisCommand(c, "set k v");
結果: type = 5
len = 2 str = OK
返回的類型5,是狀態。str是OK,代表執行成功。
3.2 get
redisReply *r2 = (redisReply*)redisCommand(c, "get k");
結果: type = 1
len = 1 str = v
返回的類型是1,字符串類型,str是‘v’ ,剛才保存的。
4 存取二進制
char sz[] = { 0,1,2,3,0 }; redisReply *r3 = (redisReply*)redisCommand(c, "set kb %b",sz,sizeof(sz));
存二進制的時候,使用%b,后面需要對應兩個參數,指針和長度。
redisReply *r4 = (redisReply*)redisCommand(c, "get kb");
讀取二進制的時候,和普通是一樣的,str字段是地址,len字段是長度。
5 存取多個值
存多個值
拼接字符串就好啦
redisReply *r5 = (redisReply*)redisCommand(c, "mset k1 v1 k2 v2");
取多個值
redisReply *r6 = (redisReply*)redisCommand(c, "mget k1 k2");
這里主要看返回值里的這兩個字段,代表返回值個數和起始地址:
size_t elements; /* number of elements, for REDIS_REPLY_ARRAY */ struct redisReply **element; /* elements vector for REDIS_REPLY_ARRAY */
知道了以上知識,基本可以上手干活了,redis的接口還是很不錯的,感覺都不用封裝了。
個人博客:http://www.fpstop.com/redis/hiredis1/