1.微软官方github下载hiredis(我下载的是redis-3.0.zip)
GitHub - microsoftarchive/redis: Redis is an in-memory database that persists on disk. The data model is key-value, but many different kind of values are supported: Strings, Lists, Sets, Sorted Sets, Hashes
2.解压后进入目录msvs,使用VS2019打开RedisServer.sln,以Debug为例:
1)直接编译hiredis生成hiredis.lib
2)直接编译Win32_interop生成Win32_interop.lib
ps:如报错,则在报错的Win32_variadicFunctor.cpp中添加#include
3.在你的项目目录下创建一个redisLib文件夹,将hiredis.lib和Win32_interop.lib放在这个文件夹下
4.右键项目,打开属性页面->C/C++
1)代码生成->运行库:选择多线程调试MTD
2)链接器->常规->附加库目录,将3中redisLib路径添加进去
3)链接器->常规->附加依赖项:输入hiredis.lib和Win32_interop.lib
5.在C++项目中引用CC头文件的部分要包括在extern "C"中,如下面例程:
#include
#ifdef __cplusplus
extern "C" {
#endif
#include "hiredis\hiredis.h"
#include "hiredis\async.h"
#include "hiredis\adapters\ae.h"
#ifdef __cplusplus
}
#endif
static aeEventLoop* loop;
static int getCallbackCalls = 0;
void getCallbackContinue(redisAsyncContext* c, void* r, void* privdata) {
redisReply* reply = (redisReply*)r;
if (reply == NULL)
return;
getCallbackCalls++;
printf("callback invoked [%d] - key:%s - value:%s\n", getCallbackCalls, (char*)privdata, reply->str);
}
void getCallbackEnd(redisAsyncContext* c, void* r, void* privdata) {
getCallbackContinue(c, r, privdata);
redisAsyncDisconnect(c);
}
void connectCallback(const redisAsyncContext* c, int status) {
if (status != REDIS_OK) {
printf("Error: %s\n", c->errstr);
return;
}
printf("Connected.\n");
}
void disconnectCallback(const redisAsyncContext* c, int status) {
if (status != REDIS_OK) {
printf("Error: %s\n", c->errstr);
return;
}
aeStop(loop);
printf("Disconnected.\n");
}
void AsyncSample() {
printf("--- ASYNC Sample Start ---\n\n");
/* The event loop must be created before the async connect */
loop = aeCreateEventLoop(1024 * 10);
redisAsyncContext* c = redisAsyncConnect("127.0.0.1", 6379);
if (c == NULL || c->err) {
if (c) {
printf("Connection error: %s\n", c->errstr);
redisAsyncFree(c);
}
else {
printf("Connection error: can't allocate redis context\n");
}
return;
}
redisAeAttach(loop, c);
redisAsyncSetConnectCallback(c, connectCallback);
redisAsyncSetDisconnectCallback(c, disconnectCallback);
char key_value[30] = "Hello World Async";
redisAsyncCommand(c, NULL, NULL, "SET key %s", key_value, strlen(key_value));
int counter = 10;
printf("Get will be called %i times.\n", counter);
for (int i = 1; i < counter; i++) {
redisAsyncCommand(c, getCallbackContinue, (char*)"0", "GET key");
}
redisAsyncCommand(c, getCallbackEnd, (char*)"0", "GET key");
aeMain(loop);
printf("\n--- ASYNC Sample Complete ---\n");
}
int main(int argc, char** argv)
{
AsyncSample();
printf("\n--- ASYNC Sample Complete ---\n");
}
6.添加ae异步通信框架:将msvs\deps下的ae.c和adlist.c添加到项目中
7.将zmalloc.h复制到msvs\deps目录下,或者调整一下ae.c中zmalloc的include的路径以免报错
------------------------------------------
注意,上述redis在使用异步方式时,虽然可以通过编译,但是无法连接,需要对redis库做一点修改才能使用,至于怎么修改,我现在没时间写,有时间再补上