Redis.h
#pragma once
#include <hiredis/hiredis.h> //把~/redis-6.0.8/deps/hiredis移到/usr/include/
#include <string>
#include <iostream>
using std::string;
using std::endl;
using std::cout;
class Redis {
public:
Redis() : _connect(NULL), _reply(NULL) {}
~Redis() {
//断开redis链接
if (_connect) {
redisFree(_connect);
}
//防止野指针
_connect = NULL;
_reply = NULL;
}
//连接redis数据库链接 两个参数分别是redis数据库的ip和端口,端口号一般为6379
bool connect(const string& ip, int port) {
_connect = redisConnect(ip.c_str(), port);
//连接后会创建(返回)上下文redisContext,这是Hiredis保持连接状态的地方
//注:redisConnect函数不是线程安全的
if (_connect == NULL || _connect->err) {
if (_connect) {
//当连接处于错误状态时,该redisContext结构具有一个err非零的整数字段。
//该字段errstr将包含带有错误描述的字符串
cout << "Error: " << _connect->errstr;
} else {
cout << "Can't allocate redis context" << endl;
}
return false;
}
cout << "Connect to Redis server success" << endl;
return true;
}
//get获取键对应的值
string get(const string& key) {
//redisCommand函数的返回值为void*,但是一般会强制转换为redisReply类型,
//以便做进一步的处理
_reply = (redisReply*)redisCommand(_connect, "GET %s", key.c_str());
cout << "Succeed to execute command: GET " << key.c_str() << endl;
if(_reply->type == REDIS_REPLY_NIL) { //该命令回复了一个nil对象。没有数据可访问。
return string("-1");
}
string value = _reply->str;
//释放redisCommand
freeReplyObject(_reply);
return value;
}
//set添加或插入键值对
void set(const string& key, const string& value) {
redisCommand(_connect, "SET %s %s", key.c_str(), value.c_str());
cout << "Succeed to execute command: SET " << key.c_str() << " " << value.c_str() << endl;
}
private:
//获取链接redis后的返回
redisContext* _connect;
//获取redisCommand的返回
redisReply* _reply;
};
Redis.cc
#include <iostream>
#include "Redis.h"
#include <string>
using namespace std;
int main()
{
Redis* predis = new Redis();
//连接redis服务器
predis->connect("127.0.0.1", 6379);//默认连接到的是 号数据库
string str;
cin >> str;
//查询str
string ret = predis->get(str);
if (ret != "-1") {
cout << "cache hit: " << str.c_str()
<< " " << ret << endl;
}
else
{
cout << "not hit" << endl;
}
//插入数据
predis->set(str, "hello");
ret = predis->get(str);
if (ret != "-1") {
cout << "cache hit: " << str.c_str()
<< " " << ret << endl;
}
else
{
cout << "not hit" << endl;
}
return 0;
}
g++ Redis.cc -lhiredis