一、C++中调用redis库
1、下载编译hiredis静态库
源码地址https://github.com/redis/hiredis
下载后解压,执行make
2、编写代码
头文件整理:将hiredis中的adapters文件夹和所有.h文件放到自己代码的头文件目录中;
库文件使用libhiredis.a,放到自己代码的库文件目录中;
2.1 连接redis
redisContext *pRedisContext;
u32 port;
std::string strRedisAddr;
std::string strRedisPassword;
BOOL32 ConnectRedis()
{
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
//连接redis服务器
pRedisContext = redisConnectWithTimeout(strRedisAddr.c_str(), port, timeout);
if (NULL == pRedisContext || 0 != pRedisContext->err)
{
if (NULL != pRedisContext)
{
printf("连接Redis失败, 错误码[%u]\n", pRedisContext->err);
redisFree(pRedisContext);
pRedisContext = NULL;
}
else
{
printf("连接Redis失败, can't allocate redis context\n");
}
return FALSE;
}