c++ 操作redis实例
Posted 春蕾夏荷
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c++ 操作redis实例相关的知识,希望对你有一定的参考价值。
1、下载redis-3.0源码,编译出redis-*.exe文件,以及一个lib文件
双击启动redis-server.exe,这是redis缓存池就建立起来了
2、使用hiredis作为基础,封装部分的方法,例如:
REDISCLIENT_API bool SetKeyValue(void* rct, const char* key, const char* value, char** errMsg)
if (NULL == rct
|| 0 == strlen(key)
|| 0 == strlen(value))
*errMsg = "invalid argument.";
return false;
char sErrMsg[MAX_ERROR_MSG_LENGTH] = 0 ;
redisContext* client = static_cast<redisContext*>(rct);
char sCommd[MAX_COMMAND_LENGTH] = 0 ;
sprintf_s(sCommd, MAX_ERROR_MSG_LENGTH, "set %s %s", key, value);
redisReply* r = (redisReply*)redisCommand(client, sCommd);
if (NULL == r)
sprintf_s(sErrMsg, MAX_ERROR_MSG_LENGTH, "Failed to Execut[set %s %s]!", key, value);
*errMsg = sErrMsg;
return false;
if (!(r->type == REDIS_REPLY_STATUS && (strcmp(r->str, "OK") == 0 || strcmp(r->str, "ok") == 0)))
sprintf_s(sErrMsg, MAX_COMMAND_LENGTH, "Failed to Execut:[%s],[%s]", sCommd, client->errstr);
*errMsg = sErrMsg;
return false;
return true;
// 获取键值
REDISCLIENT_API bool GetKeyValue(void* rct, const char* key, char** value, char** errMsg)
if (NULL == rct
|| 0 == strlen(key))
*errMsg = "invalid argument.";
return false;
redisContext* client = static_cast<redisContext*>(rct);
char sCommd[MAX_COMMAND_LENGTH] = 0 ;
char sErrMsg[MAX_ERROR_MSG_LENGTH] = 0 ;
sprintf_s(sCommd, MAX_COMMAND_LENGTH, "get %s", key);
redisReply* r = (redisReply*)redisCommand(client, sCommd);
if (NULL == r)
sprintf_s(sErrMsg, MAX_ERROR_MSG_LENGTH,"Failed to Execut[set %s %s]!", key, value);
*errMsg = sErrMsg;
return false;
if ((r->type == REDIS_REPLY_ERROR || r->type == REDIS_REPLY_NIL))
sprintf_s(sErrMsg, MAX_ERROR_MSG_LENGTH, "Failed to Execut:[%s],[%s]", sCommd, client->errstr);
*errMsg = sErrMsg;
return false;
*value = r->str;
return true;
获取或者是设置键值接口
3、使用依赖的接口:
#include "stdafx.h"
#include "Windows.h"
#include "RedisClient.h"
#include <stdlib.h>
#include <thread>
#include <mutex>
#pragma comment(lib, "../../RedisClient/Debug/RedisClient.lib")
void doAddTask()
// 链接redis
void* rct = NULL;
char* errMsg = NULL;
int bRet = ConnectRedis("127.0.0.1", 6379, "", &rct, &errMsg);
if (!bRet)
return;
char sKeyName[1024] = 0;
char sTmp[1024] = 0;
for (size_t i = 0; i < 100; ++i)
sprintf_s(sKeyName, "%d", i+10);
sprintf_s(sTmp, "%d", i);
bRet = SetKeyValue(rct, sTmp, sKeyName, &errMsg);
if (!bRet)
continue;
DisConnectRedis(rct, &errMsg);
int _tmain(int argc, _TCHAR* argv[])
// 加载redis库
bool bRet = false;
void* rct = NULL;
char* errMsg = NULL;
//插入
doAddTask();
bRet = ConnectRedis("192.168.1.12", 6379, "", &rct, &errMsg);
if (bRet)
int iNum = 0;
char* pppp = NULL;
bRet = GetKeyValue(rct, "1", &pppp, &errMsg);
DisConnectRedis(rct, &errMsg);
return 0;
至此,本地使用redis测试用例就完成了
以上是关于c++ 操作redis实例的主要内容,如果未能解决你的问题,请参考以下文章