c++调用hiredis读写redis

c++调用hiredis读写redis

  • 添加文件
  • 例子

添加文件

在工程中添加redis的c语言客户端文件,linux无需win32fixes文件
c++调用hiredis读写redis_第1张图片

例子

#ifdef _WIN32
#include "hiredis.h"

#include 
#pragma comment(lib,"wsock32.lib")
#else
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include   
#include "/home/redis/hiredis.h"

#endif
void main()
{
#ifdef _WIN32
	WORD wVerisonRequested;
	WSADATA wsaData;
	wVerisonRequested = MAKEWORD(1, 1);
	int err = WSAStartup(wVerisonRequested, &wsaData);
	if (err != 0){
		return;
	}
#endif
	//初始化redis
	struct timeval t = { 15, 500000 }; 
	redisContext *pRedisContext = redisConnectWithTimeout("192.168.190.121", 6379, t);
	if (NULL == pRedisContext || pRedisContext->err)
	{       // redis为NULL与redis->err是两种不同的错误,若redis->err为true,可使用redis->errstr查看错误信息  
	
		printf("%s \r\n", pRedisContext->errstr);
		printf("Connect to redisServer failed \n");
		return;
	}
	//输入redis密码
	const char* pcRedisPassWord = "password";
	pRedisReply = (redisReply *)redisCommand(pRedisContext, "AUTH %s", pcRedisPassWord);
	if (pRedisReply != NULL)
	{
		freeReplyObject(pRedisReply);
	}
	//用get命令获取数据	
	sprintf(pcRedisBuff, "GET %s ", "keyName");
	pRedisReply = (redisReply *)redisCommand(pRedisContext, pcRedisBuff);
	if (pRedisReply == NULL)
	{
		return;
	}
	if (pRedisReply->str == NULL)
	{
		freeReplyObject(pRedisReply);
		return;
	}
	std::string strRes(pRedisReply->str);
	freeReplyObject(pRedisReply);
	//用set指令向redis写入数据
	pRedisReply = (redisReply *)redisCommand(pRedisContext, "SET keyName value");
	if (pRedisReply != NULL)
	{
		freeReplyObject(pRedisReply);
	}
}

你可能感兴趣的:(c++调用hiredis读写redis)