C C++ redis pipeline读写数据

6 篇文章 0 订阅

pipeline (流水线)允许 Redis 客户端一次向 Redis 发送多个命令,避免了多条指令发送多次网络请求。影响处理速度。
在C,C++中,Hiredis 提供了redisAppendCommand()函数来实现流水线的命令发送方案
redisAppendCommand()会先将命令缓存起来,在调用redisGetReply()方法后一次性将命令发送给redis,并取得第一个命令的返回结果。

性能提升

在作者使用过程中,需要将原有匹配的数据scan出来,再发请求获取对应key的value,然后替换原有key,生成新的一条数据,写入redis,再删除原有的那条数据。如此操作100万条数据,时间长达10分钟以上。
改用pipeline读写后,每次操作1万条数据,100万条数据大概用时10秒。
相比较于单条操作性能提升几百倍

#include <iostream>
#include<hiredis/hiredis.h>
#include <vector>

    int pipeline_process(struct timeval access_timeout, std::vector <std::string> &pipeline_cmd,
                         std::vector <std::string> &pipeline_resp, std::vector<int> &pipeline_resp_type) {
        if (0 == context) { return -1; }
        redisSetTimeout(context, access_timeout);
        for (int i = 0; i < pipeline_cmd.size(); i++) {
            redisAppendCommand(context, pipeline_cmd[i].c_str());
        }
        for (int i = 0; i < pipeline_cmd.size(); i++) {
            int type = -1;
            std::string resp_str = "";
            redisReply *reply = 0;
            int reply_status = redisGetReply(context, (void **) &reply);
            if (reply_status == REDIS_OK && reply != NULL) {
                type = reply->type;
                if (reply->str != NULL) {
                    resp_str = reply->str;
                }
            } else {
                printf("pipeline_process error i :%d cmd : %s", i, pipeline_cmd[i].c_str());
            }
            freeReplyObject(reply);
            pipeline_resp_status.push_back(type);
            pipeline_resp.push_back(resp_str);
        }
        return 0;
    }

redis返回type

  • 根据业务需求进行状态判断
  REDIS_REPLY_STRING  : 1 
  REDIS_REPLY_ARRAY : 2
  REDIS_REPLY_INTEGER :3 
  REDIS_REPLY_NIL  : 4
  REDIS_REPLY_STATUS : 5
  REDIS_REPLY_ERROR : 6
  • 关于状态码补充说明
    • scan的正确返回状态码是REDIS_REPLY_ARRAY 2
    • get的正确返回状态码是REDIS_REPLY_STRING 1
    • set的正确返回状态码是REDIS_REPLY_STATUS 5 且reply->str为OK
    • del的正确返回状态码是REDIS_REPLY_INTEGER 3
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值