下载源代码
https://github.com/redis/hiredis
然后单独创建pro文件,将相应的.c和.h文件加进去。
然后使用vs2010(带有qt插件)打开.pro文件,编译报错
上面的为C99语法,而vs2010不支持。只能选择
https://github.com/microsoft/hiredis(c++11,vs2010不支持)
或者https://github.com/microsoftarchive/redis2.6分支
使用vs2010打开RedisServer.sln,同时添加win32fixes.c,win32fixes.h文件到hiredis项目中
右键点"重新生成"会生成hiredis.lib库
新建工程,设置并文件目录以及库目录
引入头文件
extern "C" {
#include "../../src/win32fixes.h"
}
测试代码
w32initWinSock();
redisContext *connect_context_;
redisReply *reply;
struct timeval timeout = {1, 500000};
connect_context_ = redisConnectWithTimeout((char*)"127.0.0.1", 6379, timeout);
if (connect_context_->err) {
printf("Connection error: %s\n", connect_context_->errstr);
exit(1);
}
reply = (redisReply *)redisCommand(connect_context_, "PING");
printf("PING: %s\n", reply->str);
freeReplyObject(reply);
std::string strCmd = "set test1 Test1";
{
redisReply* r = (redisReply*)redisCommand(connect_context_, strCmd.c_str());
if (NULL == r)
{
printf("Execut command1 failure\n");
return REDIS_ERR;
}
if (!(r->type == REDIS_REPLY_STATUS && (strcmp(r->str, "OK") == 0 || strcmp(r->str, "ok") == 0)))
{
printf("Failed to execute command[%s]\n", strCmd.c_str());
freeReplyObject(r);
return REDIS_ERR;
}
freeReplyObject(r);
printf("Succeed to execute command[%s]\n", strCmd.c_str());
}
//取值
strCmd = "get test1";
{
redisReply* r = (redisReply*)redisCommand(connect_context_, strCmd.c_str());
if (NULL == r)
{
printf("Execut command1 failure\n");
return REDIS_ERR;
}
if (r->type != REDIS_REPLY_STRING)
{
printf("Failed to execute command[%s]\n", strCmd.c_str());
freeReplyObject(r);
return REDIS_ERR;
}
std::string strTemp = r->str;
freeReplyObject(r);
printf("Succeed to execute command[%s], value = %s\n", strCmd.c_str(), strTemp.c_str());
}