eis/inc/zlib/RedisClient.h

127 lines
3.0 KiB
C++

#ifndef REDISCLIENT
#define REDISCLIENT
#include <hiredis/hiredis.h>
#include <iostream>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <glob/ConfigMag.h>
#include <log4cplus/LOG.h>
using std::string;
using std::cout;
using std::endl;
using namespace baosight;
using namespace log4cplus;
class RedisClient
{
public:
~RedisClient()
{
redisFree(mp_conn);
//freeReplyObject(mp_reply);
};
RedisClient()
{
LOG d("RedisClient()");
ConfigMag configmag("CRGS");
string server = configmag.ReadProperty("redis","server");
string passwd = configmag.ReadProperty("redis","passwd");
string port = configmag.ReadProperty("redis","port");
d.Info()<<"server:"<<server<<",port:"<<port<<",password:"<<passwd<<endl;
struct timeval timeout = {2,0};//2s的超时时间
mp_conn = redisConnectWithTimeout(server.c_str(), atoi(port.c_str()), timeout);
//链接错误
if(mp_conn == NULL || mp_conn->err){
if(mp_conn){
d.Error()<<"mp_connection error"<< mp_conn->errstr << endl;
}else{
d.Error()<<"cannot alloc redis context"<<endl;
}
}
//auth
mp_reply =(redisReply*)redisCommand(mp_conn, "AUTH %s",passwd.c_str());
d.Info()<<"auth is "<<mp_reply->str <<endl;
freeReplyObject(mp_reply);
}
/****
*set redis data and expire time
*key:key
*value:value data
*expiretime: expire time[s]
*/
string set(const char *key, const char *value,int expiretime = 0)
{
// LOG d("RedisClient::set");
if(key == NULL || value == NULL)
{
// d.Error() <<"key == NULL || value == NULL"<<endl;
return "key or value is null";
}
mp_reply =(redisReply*)redisCommand(mp_conn,"set %s %s",key,value);
if(expiretime > 0)
{
freeReplyObject(mp_reply);
redisCommand(mp_conn,"expire %s %d",key,expiretime);
}
string str = mp_reply->str;
freeReplyObject(mp_reply);
return str;
}
/****
*set redis data expire time
*key:key
*time: expire time[s]
*/
string expire(const char *key,int time)
{
// LOG d("RedisClient::expire");
if(key == NULL)
{
// d.Error() <<"key == NULL"<<endl;
return "key is null";
}
mp_reply =(redisReply*)redisCommand(mp_conn,"expire %s %d",key,time);
string str = mp_reply->str;
freeReplyObject(mp_reply);
return str;
}
/****
*get redis value by key
*/
string get(const char *key)
{
// LOG d("RedisClient::get");
if(key == NULL){
// d.Error()<<"key = NULL"<<endl;
return "key is null";
}
mp_reply =(redisReply*) redisCommand(mp_conn,"get %s",key);
if(mp_reply->len <= 0){
// d.Error()<<"no value"<<endl;
freeReplyObject(mp_reply);
return "null";
}
string str = mp_reply->str;
freeReplyObject(mp_reply);
return str;
}
private:
redisContext *mp_conn;
redisReply *mp_reply;
};
#endif