#include <iostream>
#include <string.h>
#include <string>
#include <stdio.h>
#include <cmath>
#include <list>
#include <algorithm>
#include <vector>
#include <hiredis/hiredis.h>
#include <stdlib.h>
class Redis
{
public:
Redis() {}
~Redis(){
this->_connect = NULL;
this->_reply = NULL;
}
bool connect(std::string host, int port){
this->_connect = redisConnect(host.c_str(), port);
if (this->_connect != NULL && this->_connect->err)
{
printf("connect error: %s\n", this->_connect->errstr);
return 0;
}
redisCommand(_connect, "auth ECoLyNEyArrQfqsZ2k");
return 1;
}
std::string get(std::string key){
this->_reply = (redisReply*)redisCommand(this->_connect, "GET %s", key.c_str());
std::string str = this->_reply->str;
freeReplyObject(this->_reply);
return str;
}
void set(std::string key, std::string value){
redisCommand(this->_connect, "SET %s %s", key.c_str(), value.c_str());
}
void setMessagelist(std::string people, std::string timeAndMessage) {
redisCommand(this->_connect, "RPUSH %s %s",people.c_str(), timeAndMessage.c_str());
}
std::string itos(int x) {
std::string result;
while (x) {
result += x % 10 + '0';
x /= 10;
}
reverse(result.begin(),result.end());
return result;
}
//获取最近number条消息
std::vector<std::string> getMessagelist(std::string people, int number) {
std::vector<std::string> result;
this->_reply = (redisReply*)redisCommand(this->_connect, "LLEN %s",people.c_str());
int len = _reply->integer;
printf("%d\n", len);
freeReplyObject(this->_reply);
printf("LRANGE %s %s %s\n", people.c_str(), itos(len - number).c_str(), itos(len - 1).c_str());
this->_reply = (redisReply*)redisCommand(this->_connect, "LRANGE %s %s %s",people.c_str(),itos(len-number).c_str(),itos(len - 1).c_str());
for (int i = 0; i < _reply->elements; i++) result.push_back(_reply->element[i]->str);
freeReplyObject(this->_reply);
return result;
}
void close() {
redisFree(_connect);
}
private:
redisContext* _connect;
redisReply* _reply;
};
int main()
{
Redis *r = new Redis();
if (!r->connect("127.0.0.1", 6379))
{
printf("connect error!\n");
return 0;
}
r->set("name", "Sitlos");
printf("Get the name is %s\n", r->get("name").c_str());
r->setMessagelist("Sitlos", "111:111");
std::vector<std::string> res= r->getMessagelist("Sitlos", 4);
for (int i = 0; i < res.size(); i++) {
printf("%s\n", res[i].c_str());
}
delete r;
return 0;
}