[转] Hiredis: redis c client使用注记

  1. 编译
  2. 使用
    • 初始化
    • 连接redis数据库

      redisContext * pConn = redisConnect(redisIp.c_str(), redisPort);
      if (m_cLocal == NULL)
      {
      return 1;
      }

      if(pConn->err)
      {
      cout << "Connection to redis[" << redisIp << "] error: " << pConn->errstr;
      redisFree(pConn);
      return 2;
      }

    • 执行命令

      string cmd="set foo bar;
      redisReply * reply=(redisReply *)redisCommand(pConn, cmd.c_str());
      if(reply == NULL)
      {
      cout << "redis[" << redisIp << "] excute " << cmd << " failed, error is: " << pConn->errstr;
      redisFree(pConn);
      pConn=NULL;
      return 3;
      }
      freeReplyObject(reply);

    • 解析结果
      • 不同的命令返回不同类型的结果,需要根据reply->type字段进行解析
  3. 注意事项

    Once an error is returned the context cannot be reused and you should set up a new connection.

    上面示例中执行命令时,如果返回了错误,则连接不可用,需要重新建立连接。

 

    更多文章,欢迎访问我的站点:零一积流

posted on 2015-09-25 12:02  零一积流  阅读(561)  评论(0编辑  收藏  举报

导航