Linux下通过hiredis操作KV数据库redis

#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;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值