Skip to content

Instantly share code, notes, and snippets.

@luchenqun
Created January 10, 2018 10:10
Show Gist options
  • Select an option

  • Save luchenqun/45354d90a42a3f38016f37299c9e5fff to your computer and use it in GitHub Desktop.

Select an option

Save luchenqun/45354d90a42a3f38016f37299c9e5fff to your computer and use it in GitHub Desktop.
class Redis
{
public:
redisContext* context;
Redis(const char * ip="127.0.0.1",int port=6379){
this->context = redisConnect(ip,port);
if(this->context == NULL || context->err){
if(context){
printf("Error: %s\n",context->errstr);
exit(-1);
}else{
printf("can not allocate redis context\n");
exit(-1);
}
}
}
string hget(const char* key,const char* hkey){
const char* argv[3];
size_t argvlen[3];
argv[0] = "HGET";
argvlen[0] = 4;
argv[1] = key;
argvlen[1] = strlen(key);
argv[2] = hkey;
argvlen[2] = strlen(hkey);
redisReply* reply =(redisReply*) redisCommandArgv(this->context, 3, argv, argvlen);
string value;
if(reply->type != REDIS_REPLY_NIL){
value = string(reply->str,reply->str + reply->len);
}
freeReplyObject(reply);
return value;
}
int hset(const char* key, const char* hkey, const char* value){
redisReply* reply =(redisReply*) redisCommand(this->context, "HSET %s %s %s",key,hkey, value);
freeReplyObject(reply);
return 1;
}
int hset(const char* key,const char* hkey,const char* hvalue, size_t hvaluelen){
const char* argv[4];
size_t argvlen[4];
argv[0] = "HSET";
argvlen[0] = 4;
argv[1] = key;
argvlen[1] = strlen(key);
argv[2] = hkey;
argvlen[2] = strlen(hkey);
argv[3] = hvalue;
argvlen[3] = hvaluelen;
redisReply * reply =(redisReply*) redisCommandArgv(this->context, 4, argv, argvlen);
freeReplyObject(reply);
return 1;
}
/**delete key*/�
int del(const char* key){
int res = 0;4
redisReply* reply = (redisReply*)redisCommand(this->context, "DEL %s", key);
if(reply->type == REDIS_REPLY_INTEGER){
if(reply->integer == 1L)
res = 1;
}
freeReplyObject(reply);
return res;
}
/*if Key ID exists*/
int existsKey(const char* ID){
redisReply * reply = (redisReply*)redisCommand(this->context,"exists %s",ID);
int res = 0;
if(reply->type == REDIS_REPLY_INTEGER){
if(reply->integer == 1L)
res = 1;
}
freeReplyObject(reply);
return res;
}
virtual ~Redis(){
redisFree(this->context);
}
protected:
private:
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment