找回密码
 用户注册

QQ登录

只需一步,快速开始

查看: 9287|回复: 0

Redis学习手册(实例代码)

[复制链接]
发表于 2012-4-18 14:06:58 | 显示全部楼层 |阅读模式
   在之前的博客中已经非常详细的介绍了Redis的各种操作命令、运行机制和服务器初始化参数配置。本篇博客是该系列博客中的最后一篇,在这里将给出基于Redis客户端组件访问并操作Redis服务器的代码示例。然而需要说明的是,由于Redis官方并未提供基于C接口的Windows平台客户端,因此下面的示例仅可运行于Linux/Unix平台。但是对于使用其它编程语言的开发者而言,如C#和Java,Redis则提供了针对这些语言的客户端组件,通过该方式,同样可以达到基于Windows平台与Redis服务器进行各种交互的目的。
    该篇博客中使用的客户端来自于Redis官方网站,是Redis推荐的基于C接口的客户端组件,见如下链接:
    https://github.com/antirez/hiredis
    在下面的代码示例中,将给出两种最为常用的Redis命令操作方式,既普通调用方式和基于管线的调用方式。
    注:在阅读代码时请留意注释。

    1. #include <stdio.h>
    2. #include <stdlib.h>
    3. #include <stddef.h>
    4. #include <stdarg.h>
    5. #include <string.h>
    6. #include <assert.h>
    7. #include <hiredis.h>
    8. void doTest()
    9. {
    10.      int timeout = 10000;
    11.      struct timeval tv;
    12.      tv.tv_sec = timeout / 1000;
    13.      tv.tv_usec = timeout * 1000;
    14.      //以带有超时的方式链接Redis服务器,同时获取与Redis连接的上下文对象。
    15.      //该对象将用于其后所有与Redis操作的函数。
    16.      redisContext* c = redisConnectWithTimeout("192.168.149.137",6379,tv);
    17.      if (c->err) {
    18.          redisFree(c);
    19.          return;
    20.      }
    21.      const char* command1 = "set stest1 value1";
    22.      redisReply* r = (redisReply*)redisCommand(c,command1);
    23.      //需要注意的是,如果返回的对象是NULL,则表示客户端和服务器之间出现严重错误,必须重新链接。
    24.      //这里只是举例说明,简便起见,后面的命令就不再做这样的判断了。
    25.      if (NULL == r) {
    26.          redisFree(c);
    27.          return;
    28.      }
    29.      //不同的Redis命令返回的数据类型不同,在获取之前需要先判断它的实际类型。
    30.      //至于各种命令的返回值信息,可以参考Redis的官方文档,或者查看该系列博客的前几篇
    31.      //有关Redis各种数据类型的博客。:)
    32.      //字符串类型的set命令的返回值的类型是REDIS_REPLY_STATUS,然后只有当返回信息是"OK"
    33.      //时,才表示该命令执行成功。后面的例子以此类推,就不再过多赘述了。
    34.      if (!(r->type == REDIS_REPLY_STATUS && strcasecmp(r->str,"OK") == 0)) {
    35.          printf("Failed to execute command[%s].\n",command1);
    36.          freeReplyObject(r);
    37.          redisFree(c);
    38.          return;
    39.      }
    40.      //由于后面重复使用该变量,所以需要提前释放,否则内存泄漏。
    41.      freeReplyObject(r);
    42.      printf("Succeed to execute command[%s].\n",command1);
    43.      const char* command2 = "strlen stest1";
    44.      r = (redisReply*)redisCommand(c,command2);
    45.      if (r->type != REDIS_REPLY_INTEGER) {
    46.          printf("Failed to execute command[%s].\n",command2);
    47.          freeReplyObject(r);
    48.          redisFree(c);
    49.          return;
    50.      }
    51.      int length = r->integer;
    52.      freeReplyObject(r);
    53.      printf("The length of 'stest1' is %d.\n",length);
    54.      printf("Succeed to execute command[%s].\n",command2);
    55.      const char* command3 = "get stest1";
    56.      r = (redisReply*)redisCommand(c,command3);
    57.      if (r->type != REDIS_REPLY_STRING) {
    58.          printf("Failed to execute command[%s].\n",command3);
    59.          freeReplyObject(r);
    60.          redisFree(c);
    61.          return;
    62.      }
    63.      printf("The value of 'stest1' is %s.\n",r->str);
    64.      freeReplyObject(r);
    65.      printf("Succeed to execute command[%s].\n",command3);
    66.      const char* command4 = "get stest2";
    67.      r = (redisReply*)redisCommand(c,command4);
    68.      //这里需要先说明一下,由于stest2键并不存在,因此Redis会返回空结果,这里只是为了演示。
    69.      if (r->type != REDIS_REPLY_NIL) {
    70.          printf("Failed to execute command[%s].\n",command4);
    71.          freeReplyObject(r);
    72.          redisFree(c);
    73.          return;
    74.      }
    75.      freeReplyObject(r);
    76.      printf("Succeed to execute command[%s].\n",command4);
    77.      const char* command5 = "mget stest1 stest2";
    78.      r = (redisReply*)redisCommand(c,command5);
    79.      //不论stest2存在与否,Redis都会给出结果,只是第二个值为nil。
    80.      //由于有多个值返回,因为返回应答的类型是数组类型。
    81.      if (r->type != REDIS_REPLY_ARRAY) {
    82.          printf("Failed to execute command[%s].\n",command5);
    83.          freeReplyObject(r);
    84.          redisFree(c);
    85.          //r->elements表示子元素的数量,不管请求的key是否存在,该值都等于请求是键的数量。
    86.          assert(2 == r->elements);
    87.          return;
    88.      }
    89.      for (int i = 0; i < r->elements; ++i) {
    90.          redisReply* childReply = r->element[i];
    91.          //之前已经介绍过,get命令返回的数据类型是string。
    92.          //对于不存在key的返回值,其类型为REDIS_REPLY_NIL。
    93.          if (childReply->type == REDIS_REPLY_STRING)
    94.              printf("The value is %s.\n",childReply->str);
    95.      }
    96.      //对于每一个子应答,无需使用者单独释放,只需释放最外部的redisReply即可。
    97.      freeReplyObject(r);
    98.      printf("Succeed to execute command[%s].\n",command5);
    99.      printf("Begin to test pipeline.\n");
    100.      //该命令只是将待发送的命令写入到上下文对象的输出缓冲区中,直到调用后面的
    101.      //redisGetReply命令才会批量将缓冲区中的命令写出到Redis服务器。这样可以
    102.      //有效的减少客户端与服务器之间的同步等候时间,以及网络IO引起的延迟。
    103.      //至于管线的具体性能优势,可以考虑该系列博客中的管线主题。
    104.      if (REDIS_OK != redisAppendCommand(c,command1)
    105.          || REDIS_OK != redisAppendCommand(c,command2)
    106.          || REDIS_OK != redisAppendCommand(c,command3)
    107.          || REDIS_OK != redisAppendCommand(c,command4)
    108.          || REDIS_OK != redisAppendCommand(c,command5)) {
    109.          redisFree(c);
    110.          return;
    111.      }
    112.      redisReply* reply = NULL;
    113.      //对pipeline返回结果的处理方式,和前面代码的处理方式完全一直,这里就不再重复给出了。
    114.      if (REDIS_OK != redisGetReply(c,(void**)&reply)) {
    115.          printf("Failed to execute command[%s] with Pipeline.\n",command1);
    116.          freeReplyObject(reply);
    117.          redisFree(c);
    118.      }
    119.      freeReplyObject(reply);
    120.      printf("Succeed to execute command[%s] with Pipeline.\n",command1);
    121.      if (REDIS_OK != redisGetReply(c,(void**)&reply)) {
    122.          printf("Failed to execute command[%s] with Pipeline.\n",command2);
    123.          freeReplyObject(reply);
    124.          redisFree(c);
    125.      }
    126.      freeReplyObject(reply);
    127.      printf("Succeed to execute command[%s] with Pipeline.\n",command2);
    128.      if (REDIS_OK != redisGetReply(c,(void**)&reply)) {
    129.          printf("Failed to execute command[%s] with Pipeline.\n",command3);
    130.          freeReplyObject(reply);
    131.          redisFree(c);
    132.      }
    133.      freeReplyObject(reply);
    134.      printf("Succeed to execute command[%s] with Pipeline.\n",command3);
    135.      if (REDIS_OK != redisGetReply(c,(void**)&reply)) {
    136.          printf("Failed to execute command[%s] with Pipeline.\n",command4);
    137.          freeReplyObject(reply);
    138.          redisFree(c);
    139.      }
    140.      freeReplyObject(reply);
    141.      printf("Succeed to execute command[%s] with Pipeline.\n",command4);
    142.      if (REDIS_OK != redisGetReply(c,(void**)&reply)) {
    143.          printf("Failed to execute command[%s] with Pipeline.\n",command5);
    144.          freeReplyObject(reply);
    145.          redisFree(c);
    146.      }
    147.      freeReplyObject(reply);
    148.      printf("Succeed to execute command[%s] with Pipeline.\n",command5);
    149.      //由于所有通过pipeline提交的命令结果均已为返回,如果此时继续调用redisGetReply,
    150.      //将会导致该函数阻塞并挂起当前线程,直到有新的通过管线提交的命令结果返回。
    151.      //最后不要忘记在退出前释放当前连接的上下文对象。
    152.      redisFree(c);
    153.      return;
    154. }
    155. int main()
    156. {
    157.      doTest();
    158.      return 0;
    159. }
    160. //输出结果如下:
    161. //Succeed to execute command[set stest1 value1].
    162. //The length of 'stest1' is 6.
    163. //Succeed to execute command[strlen stest1].
    164. //The value of 'stest1' is value1.
    165. //Succeed to execute command[get stest1].
    166. //Succeed to execute command[get stest2].
    167. //The value is value1.
    168. //Succeed to execute command[mget stest1 stest2].
    169. //Begin to test pipeline.
    170. //Succeed to execute command[set stest1 value1] with Pipeline.
    171. //Succeed to execute command[strlen stest1] with Pipeline.
    172. //Succeed to execute command[get stest1] with Pipeline.
    173. //Succeed to execute command[get stest2] with Pipeline.
    174. //Succeed to execute command[mget stest1 stest2] with Pipeline.
    复制代码
    该示例代码已经调试通过,同时也用Valgrind进行了运行时检查,不存在任何内存泄露,特此声明。



目录:
Redis学习手册(开篇)
http://www.acejoy.com/ace/thread-4288-1-1.html
一、简介
二、Redis的优势
三、目前版本中Redis存在的主要问题
四、和关系型数据库的比较
五、如何持久化内存数据

Redis学习手册(String数据类型)
http://www.acejoy.com/ace/thread-4289-1-1.html
一、概述
二、相关命令列表
三、命令示例

Redis学习手册(List数据类型)
http://www.acejoy.com/ace/thread-4290-1-1.html
一、概述
二、相关命令列表
三、命令示例
四、链表结构的小技巧

Redis学习手册(Set数据类型)
http://www.acejoy.com/ace/thread-4291-1-1.html
一、概述
二、相关命令列表
三、命令示例
四、应用范围

Redis学习手册(Hashes数据类型)
http://www.acejoy.com/ace/thread-4292-1-1.html
一、概述
二、相关命令列表
三、命令示例

Redis学习手册(Sorted-Sets数据类型)
http://www.acejoy.com/ace/thread-4293-1-1.html
一、概述
二、相关命令列表
三、命令示例
四、应用范围

Redis学习手册(Key操作命令)
http://www.acejoy.com/ace/thread-4294-1-1.html
一、概述
二、相关命令列表
三、命令示例

Redis学习手册(事务)
http://www.acejoy.com/ace/thread-4295-1-1.html
一、概述
二、相关命令列表
三、命令示例
四、WATCH命令和基于CAS的乐观锁

Redis学习手册(主从复制)
http://www.acejoy.com/ace/thread-4296-1-1.html
一、Redis的Replication
二、Replication的工作原理
三、如何配置Replication
四、应用示例

Redis学习手册(持久化)
http://www.acejoy.com/ace/thread-4297-1-1.html
一、Redis提供了哪些持久化机制
二、RDB机制的优势和劣势
三、AOF机制的优势和劣势
四、其它

Redis学习手册(虚拟内存)
http://www.acejoy.com/ace/thread-4298-1-1.html
一、简介
二、应用场景
三、配置

Redis学习手册(管线)
http://www.acejoy.com/ace/thread-4299-1-1.html
一、请求应答协议和RTT
二、管线(pipelining)
三、Benchmark

Redis学习手册(服务器管理)
http://www.acejoy.com/ace/thread-4300-1-1.html
一、概述
二、相关命令列表
   
Redis学习手册(内存优化)
http://www.acejoy.com/ace/thread-4301-1-1.html
一、特殊编码
二、BIT和Byte级别的操作
三、尽可能使用Hash

Redis学习手册(实例代码)
http://www.acejoy.com/ace/thread-4302-1-1.html


您需要登录后才可以回帖 登录 | 用户注册

本版积分规则

Archiver|手机版|小黑屋|ACE Developer ( 京ICP备06055248号 )

GMT+8, 2024-4-23 21:58 , Processed in 0.021724 second(s), 6 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表