redis.cpp
#ifndef REDIS_GHQ
#define REDI_GHQ
#include<iostream>
#include<hiredis/hiredis.h>
using namespace std;
class Redis
{
public:
Redis(){
_conn=NULL;
_reply=NULL;
}
~Redis(){
_conn=NULL;
_reply=NULL;
}
bool connect(string host,int port){
_conn = redisConnect(host.c_str(),port);
if(_conn!=NULL&&_conn->err){
cout<<"连接失败:"<<_conn->err<<endl;
return 0;
}
return 1;
}
void set(string key,string value){
redisCommand(_conn,"set %s %s",key.c_str(),value.c_str());
}
string get(string key){
_reply = static_cast<redisReply*> (redisCommand(_conn,"get %s",key.c_str()));
string s = _reply->str;
freeReplyObject(_reply);
return s;
}
private:
redisContext* _conn;
redisReply * _reply;
};
#endif
main.cpp
#include"redis.cpp"
#include<bits/stdc++.h>
using namespace std;
int main(){
Redis* re = new Redis();
if(re->connect("127.0.0.1",6379)){
cout<<"连接成功";
string k,v;
cin>>k>>v;
while(k!="#"){
re->set(k,v);
cout<<re->get(k);
cin>>k>>v;
}
}
delete re;
return 0;
}
编译:g++ main.cpp -o redis -L/usr/local/lib/ -lhiredis
运行:./redis
结果:
连接成功
name ghq
ghq
age1 165
165
^C
注意:
1、需要提前./redis-server打开redis
pipeline操作:
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;
}
参数:
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处理的多个请求返回的状态