使用hiredis实现pipeline方式访问
1.介绍
hiredis:
一个c/c++的访问redis的api库
地址:https://github.com/redis/hiredis
pipeline方式:
redis中的pipeline方式,指的是把多次请求交互封装到一次完成,只交互一次,类似于多个请求“批处理”成一次交互
好处:
同样是多次请求,用pipeline方式比多次请求的总的延时低,交互次数少,
即低延迟,高吞吐。
2.代码
int pipeline_process(struct timeval access_timeout, std::vector<std::string> & pipeline_cmd, std::vector<std::string> &pipeline_resp, std::vector<bool> &pipeline_resp_status)
{
if (0 == redis_ctx) {return -1;}
redisSetTimeout(redis_ctx, access_timeout);
for (int i = 0; i < pipeline_cmd.size();i++)
{
redisAppendCommand(redis_ctx, pipeline_cmd[i].c_str());
}
for (int i = 0; i < pipeline_cmd.size();i++)
{
bool status = false;
std::string resp_str = "";
redisReply *reply = 0;
if(redisGetReply(redis_ctx, (void **)&reply) == REDIS_OK
&& reply != NULL
&& reply->type == REDIS_REPLY_STRING)
{
status = true;
resp_str = reply->str;
}
//free
freeReplyObject(reply);
pipeline_resp_status.push_back(status);
pipeline_resp.push_back(resp_str);
}
return 0;
}
3.解释:
参数:
struct timeval access_timeout:访问的超时时间
std::vector<std::string> & pipeline_cmd:pipeline处理的多个请求命令字符串
std::vector<std::string> &pipeline_resp:pipeline处理的多个请求返回的字符串
std::vector<bool> &pipeline_resp_status:pipeline处理的多个请求返回的状态

浙公网安备 33010602011771号