a8/a8/redis.cc
2018-08-26 20:34:01 +08:00

126 lines
3.1 KiB
C++

#include <a8/a8.h>
#include <a8/redis.h>
static a8::XValue RedisReplyToXValue(redisReply* reply)
{
if(reply){
switch(reply->type){
case REDIS_REPLY_STRING:
{
a8::XValue val;
val.SetDynData(reply->str, reply->len);
return val;
}
break;
case REDIS_REPLY_INTEGER:
{
return a8::XValue(reply->integer);
}
break;
case REDIS_REPLY_NIL:
{
a8::XValue val;
val.Set("");
return val;
}
break;
case REDIS_REPLY_ARRAY:
{
a8::XValue val;
val.SetUserData(reply->element, reply->elements);
return val;
}
break;
default:
return a8::XValue();
}
}else{
return a8::XValue();
}
}
namespace a8
{
Redis::Redis()
{
}
Redis::~Redis()
{
if (redis_) {
redisFree(redis_);
redis_ = nullptr;
}
}
bool Redis::Connect(const std::string& host, int port, int timeout)
{
if (redis_) {
redisFree(redis_);
redis_ = nullptr;
}
host_ = host;
port_ = port;
timeout_ = timeout;
struct timeval tv;
tv.tv_sec = timeout_ / 1000;
tv.tv_usec = timeout_ * 1000;
redis_ = redisConnectWithTimeout(host_.c_str(), port_, tv);
return redis_ && !redis_->err;
}
bool Redis::Ping()
{
auto ret = ExecCommand("PING");
return std::get<0>(ret);
}
std::tuple<bool, a8::XValue> Redis::ExecCommand(const std::string& command)
{
if (!redis_) {
return std::make_tuple(false, a8::XValue());
}
redisReply *reply = (redisReply*)redisCommand(redis_, command.c_str());
return std::make_tuple(false, RedisReplyToXValue(reply));
}
std::tuple<bool, a8::XValue> Redis::HGet(const std::string& key, const std::string& field)
{
return ExecCommand(a8::Format("hget %s %s", {key, field}));
}
std::tuple<bool, a8::XValue> Redis::HSet(const std::string& key, const std::string& field, a8::XValue& val)
{
return ExecCommand(a8::Format("hset %s %s %s", {key, field, val}));
}
std::tuple<bool, a8::XValue> Redis::HDel(const std::string& key)
{
return ExecCommand(a8::Format("hdel %s", {key}));
}
std::tuple<bool, a8::XValue> Redis::Get(const std::string& key)
{
return ExecCommand(a8::Format("get %s", {key}));
}
std::tuple<bool, a8::XValue> Redis::Set(const std::string& key, a8::XValue& val)
{
return ExecCommand(a8::Format("set %s %s", {key, val}));
}
std::tuple<bool, a8::XValue> Redis::Del(const std::string& key)
{
return ExecCommand(a8::Format("del %s", {key}));
}
std::tuple<bool, a8::XValue> Redis::PExpire(const std::string& key, unsigned short mill_sec)
{
return ExecCommand(a8::Format("pexpire %s %d", {key, mill_sec}));
}
}