Redis学习之路(005)- redis内存数据库C客户端hiredis API 中文说明

A)编译安装

make
make install (/usr/local)
make install PREFIX=$HOME/progs(可以自由指定安装路径)

B)同步的API接口

redisContext *redisConnect(const char *ip, int port);
void *redisCommand(redisContext *c, const char *format, ...);
void freeReplyObject(void *reply);

1)建立连接

redisContext *c = redisConnect("127.0.0.1", 6379);
if (c != NULL && c->err) {
        printf("Error: %s\n", c->errstr);
            // handle error
}

redisConnect函数用来创建一个叫redisContext的东西,它包含了连接相关的信息,它里面有个err字段,0表示正常,其他表示出错了!通过errstr字段可以知晓错误信息。


2)执行命令

reply = redisCommand(context, "SET key value");
reply = redisCommand(context, "SET key %s", value);
reply = redisCommand(context, "SET key %b", value, (size_t) valuelen);
reply = redisCommand(context, "SET key:%s %s", myid, value);

redisCommand的调用格式类似printf函数,上面的第二条调用语句的作用在于输入二进制格式的value内容,其后必须表明二进制的字节长度!


3)redisCommand函数返回一个东西叫redisReply,我们需要通过判断它的type字段来知道返回了具体什么样的内容:

REDIS_REPLY_STATUS      表示状态,内容通过str字段查看,字符串长度是len字段
REDIS_REPLY_ERROR       表示出错,查看出错信息,如上的str,len字段
REDIS_REPLY_INTEGER    返回整数,从integer字段获取值
REDIS_REPLY_NIL            没有数据返回
REDIS_REPLY_STRING      返回字符串,查看str,len字段
REDIS_REPLY_ARRAY       返回一个数组,查看elements的值(数组个数),通过element[index]的方式访问数组元素,每个数组元素是 一个redisReply对象的指针

4)另外有一个类似的函数,批量执行命令:

void *redisCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen);

5)redisReply使用完毕后,需要使用函数freeReplyObject进行释放销毁

void redisFree(redisContext *c)的作用是断开连接,并释放redisContext的内容

6)redisCommand的函数执行流程说明:
  a.格式化Redis command
  b.格式化后的命令内容放入redisContext的输出缓冲区
  c.调用redisGetReply函数执行命令,得到结果

7)管道的使用方式:
a.填入需要执行的命令

void redisAppendCommand(redisContext *c, const char *format, ...);
void redisAppendCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen);

b.获取命令的输出结果

int redisGetReply(redisContext *c, void **reply);

c.释放输出结果

void freeReplyObject(void *reply);

例子:

redisReply *reply = NULL;
redisAppendCommand(context,"set key1 value");
redisAppendCommand(context,"get key2");
redisGetReply(context,&reply); // reply for set
freeReplyObject(reply);
redisGetReply(context,&reply); // reply for get
freeReplyObject(reply);

订阅模式:

reply = redisCommand(context,"SUBSCRIBE test");
freeReplyObject(reply);
while(redisGetReply(context,&reply) == REDIS_OK) {
        // consume message
        freeReplyObject(reply);
}

8)redisReply返回结果处理:

REDIS_OK                    正常
REDIS_ERR_IO          IO读/写出现异常,通过errno查看原因
REDIS_ERR_EOF            服务器关闭了链接,读结束
REDIS_ERR_PROTOCOL  分析redis协议内容出错
EDIS_ERR_OTHER          其他未知的错误
上述错误类型都可以通过redisReply的errstr字段查看简短的描述

 C)异步API(异步API的使用方式和同步API差不多,在这儿列出不同的函数吧)

1.连接redis服务器

redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
if (c->err) {
        printf("Error: %s\n", c->errstr);
            // handle error
}

2.设置连接、断开的钩子函数

int redisAsyncSetConnectCallback(redisAsyncContext *ac, redisConnectCallback *fn);
int redisAsyncSetDisconnectCallback(redisAsyncContext *ac, redisDisconnectCallback *fn);

3.插入命令信息

int redisAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata,const char *format, ...);
int redisAsyncCommandArgv( redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, int argc, const char **argv, const size_t *argvlen);

获取命令输出和同步API相同


4.关闭连接

void redisAsyncDisconnect(redisAsyncContext *ac);


D)辅助API
下面的API主要用于其他编程语言绑定的术后,可以读取分析数据

redisReader *redisReaderCreate(void);
void redisReaderFree(redisReader *reader);
int redisReaderFeed(redisReader *reader, const char *buf, size_t len);
int redisReaderGetReply(redisReader *reader, void **reply);

官方例子:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <hiredis.h> 
 5 
 6 int main(int argc, char **argv) {
 7     unsigned int j;
 8     redisContext *c;
 9     redisReply *reply;
10     const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1";
11     int port = (argc > 2) ? atoi(argv[2]) : 6379;
12     struct timeval timeout = { 1, 500000 }; // 1.5 seconds
13     c = redisConnectWithTimeout(hostname, port, timeout);
14         if (c == NULL || c->err) {
15             if (c) {
16                 printf("Connection error: %s\n", c->errstr);
17                 redisFree(c);
18             } else {
19                 printf("Connection error: can't allocate redis context\n");
20             }
21             exit(1);
22         }
23         
24         /* PING server */
25         reply = redisCommand(c,"PING");
26         printf("PING: %s\n", reply->str);
27         freeReplyObject(reply);
28         
29     /* Set a key */
30     reply = redisCommand(c,"SET %s %s", "foo", "hello world");
31     printf("SET: %s\n", reply->str);
32     freeReplyObject(reply);
33         
34         /* Set a key using binary safe API */
35         reply = redisCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5);
36         printf("SET (binary API): %s\n", reply->str);
37         freeReplyObject(reply);
38         
39     /* Try a GET and two INCR */
40     reply = redisCommand(c,"GET foo");
41     printf("GET foo: %s\n", reply->str);
42     freeReplyObject(reply);
43     reply = redisCommand(c,"INCR counter");
44     printf("INCR counter: %lld\n", reply->integer);
45     freeReplyObject(reply);
46     
47     /* again ... */
48     reply = redisCommand(c,"INCR counter");
49     printf("INCR counter: %lld\n", reply->integer);
50     freeReplyObject(reply);
51     
52     /* Create a list of numbers, from 0 to 9 */    
53     reply = redisCommand(c,"DEL mylist");
54     freeReplyObject(reply);
55     for (j = 0; j < 10; j++) {
56         char buf[64];
57         snprintf(buf,64,"%d",j);
58         reply = redisCommand(c,"LPUSH mylist element-%s", buf);
59         freeReplyObject(reply);
60     }
61     
62     /* Let's check what we have inside the list */
63     reply = redisCommand(c,"LRANGE mylist 0 -1");
64     if (reply->type == REDIS_REPLY_ARRAY) {
65         for (j = 0; j < reply->elements; j++) {
66             printf("%u) %s\n", j, reply->element[j]->str);
67         }
68     }
69     freeReplyObject(reply);
70     /* Disconnects and frees the context */
71     redisFree(c);
72     return 0;
73 }

 

posted @ 2017-05-21 18:39  极客先锋  阅读(444)  评论(0编辑  收藏  举报