Redis简单使用(C++)

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值