use_redis.h
#ifndef _REDIS_H_
#define _REDIS_H_
#include <iostream>
#include <string.h>
#include <string>
#include <stdio.h>
#include <hiredis/hiredis.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;
}
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());
}
private:
redisContext* _connect;
redisReply* _reply;
};
#endif //_REDIS_H_
use_redis.cpp
#include "use_redis.h"
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
void showRank()
{
redisContext * pConn = redisConnect("192.168.10.119", 6379);
if (NULL == pConn)
{
printf("redisConnect err\n");
return ;
}
while(1)
{
#ifdef _WIN32
Sleep(1000); //休眠1秒
#else //linux
sleep(1); //休眠1秒
#endif
redisReply *pRet = (redisReply *)redisCommand(pConn, "zrevrange players 0 5 withscores");
if(NULL == pRet)
{
printf("获取前五失败\n");
continue;
}
printf("======================\n");
int i =0;
for(i = 0; i < pRet->elements; i++)
{
std::cout << pRet->element[i]->str << std::endl;
}
printf("======================\n");
}
}
int main()
{
showRank();
#if 0
Redis *r = new Redis();
if(!r->connect("192.168.10.119", 6379))
{
printf("connect error!\n");
return 0;
}
r->set("name", "Andy");
printf("Get the name is %s\n", r->get("name").c_str());
delete r;
#endif
return 0;
}
Makefile
redis: *.cpp *.h
g++ use_redis.cpp -o test -L/usr/local/lib/ -lhiredis
clean:
rm test.o redis