hiredis api学习

来源:互联网 发布:佛教的软件 编辑:程序博客网 时间:2024/06/06 12:51
hiredis API接口

1、redisConnect(const char *ip, int port)
   ip: 主机ip地址
   port: 主机端口
   功能:连接到redis服务器,创建redisContext结构,redisContext是hiredis持有的连接状态。
  
2、redisCommand(redisContext *c, char *cmd)
   c: redisConnect调用后返回的redisContext指针
   cmd:redis 命令字符串,如“set foo bar”
   功能:给redis服务器发送命令
   如果要发送二进制安全命令,则可以采用%b的格式化方式,同时需要一个字符串指针和size_t类型的字符串长度参数。


3、freeReplyObject(redisReply *reply)
   r: redisCommand调用返回的redisReply指针
   功能:释放redisReply对象
   在使用异步api时会自动释放


4、redisCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen)
   c: redisConnect调用返回的指针
   argc:传递参数的个数, 
   argv:主要用于传递的string的value
   argvlen: 每个string的size
   功能:传递多个命令参数


5、redisAppendCommand(redisContext *c, const char *format, ...)
   c:redisConnect调用后返回的redisContext指针
   format:命令字符串
   功能:在管线命令中应用,与redisCommand类似,但不返回reply


6、redisAppendCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen)
   同上,一次发送多命令参数


7、redisGetReply(redisContext *c,void **reply)
   c:redisConnect调用后返回的redisContext指针
   reply:一个指向空类型的双重指针
   功能:获取c中的reply


8、关于异步API,正在学习中


一个简单的小程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#include <hiredis.h>


int main(int argc,char **argv)
{
    redisContext *c;
    redisReply *r;
    const char *hostname = argv[1];
    int port = atoi(argv[2]);
    
    struct timeval timeout = {1,500000};
    c = redisConnectWithTimeout(hostname,port,timeout); //connect to server
    if( (c == NULL) || (c->err) )
    {
if(c)
{
  printf("error %s\n",c->errstr);
}
else
{
  printf("Connection error: can't allocate redis context\n");
}
     }
     
     r = redisCommand(c,"PING"); //send command
     printf("PING:%s\n",r->str);
     freeReplyObject(r);
#if 1
     r = redisCommand(c,"SET foo hello");
     printf("SET foo hello:%s\n",r->str);
     freeReplyObject(r);


     r = redisCommand(c,"GET foo");
     printf("GET foo:%s\n",r->str);
     freeReplyObject(r);


     r = redisCommand(c,"SET bar %s","hello",(size_t) 5);
     printf("SET bar hello:%s\n",r->str);
     freeReplyObject(r);


     r = redisCommand(c,"GET bar");
     printf("GET bar:%s\n",r->str);
     freeReplyObject(r);


     r = redisCommand(c,"INCR counter");
     printf("INCR counter:%lld\n",r->integer);
     freeReplyObject(r);


     printf("pipelining test:\n"); // 管线命令
     void *re; // int redisGetReply(redisContext *c, void **reply) 这里reply是 **void类型,所以重新定义了一个void *类型的变量


     redisAppendCommand(c,"INCR counter");
     redisAppendCommand(c,"INCR counter");
     redisGetReply(c,&re);
     printf("incr:%lld\n",r->integer);
     freeReplyObject(re);
     redisGetReply(c,&re);
     printf("incr:%lld\n",r->integer);
     freeReplyObject(re);
#endif
     redisFree(c);
     return 0;
}
0 0