windows c++使用hiredis同步模式实现发布订阅

来源:互联网 发布:北京南站离北京站源码 编辑:程序博客网 时间:2024/06/06 03:13

//参考网址

     http://blog.csdn.net/lls2012/article/details/71123099


#include <iostream>

using namespace std;
#include"hiredis.h"

int main()
{
//初始化
int ret = redisNetInit();
if(ret == 0)
{
printf("redisNetInit fail!");
return -1;
}


//通过ip.port连接redis服务(默认监听端口为6379)
timeval t;
t.tv_sec = 500;
redisContext* redis = redisConnectWithTimeout("192.168.13.167", 6379,t);
if (NULL == redis || redis->err)
{       
//释放redis连接
redisFree(redis); 
printf("Connect to redisServer fail\n");
return -1;
}
printf("Connect to redisServer Success\n");


//REDIS://192.168.107.89.6379/2edcdb0c-4414-5631-b628-3f3c11bb2c7a
//SUBSCRIBE命令用于订阅给定的一个或多个频道的信息(SUBSCRIBE:发布订阅的命令)
std::string command = "SUBSCRIBE ";

command += "eventChannel";


        redisReply * reply = (redisReply *)redisCommand(redis,command.c_str());  
freeReplyObject(reply);

while (redisGetReply(redis, (void **)&reply) == REDIS_OK)  
{  
if (reply == NULL)  
{  
printf("Execut command failure\n");
// 命令执行失败,释放内存  
Sleep(2000);
continue;
}

if (!(reply->type == REDIS_REPLY_ARRAY && reply->elements == 3))
{       
// 判断命令执行的返回值  
printf("Failed to execute command[%s]\n", command);
freeReplyObject(reply);
Sleep(2000);
continue;
}
//输出结果
for (int i = 0; i < reply->elements; i++)  
{  
printf("%d)%s\n", i + 1, reply->element[i]->str);  
}  
freeReplyObject(reply);  
}  
redisFree(redis); 


#if 0
while (1)
{
//执行redis数据库中的操作命令(结果强转成redisReply*类型)
redisReply* reply = (redisReply*)redisCommand(redis,command.c_str());
if (NULL == reply)
{
printf("Execut command failure\n");
// 命令执行失败,释放内存  
Sleep(2000);
continue;
}
freeReplyObject(reply);


redisGetReply(redis, (void **)&reply);


if (!(reply->type == REDIS_REPLY_ARRAY && reply->elements == 3))
{       
// 判断命令执行的返回值  
printf("Failed to execute command[%s]\n", command);
freeReplyObject(reply);
Sleep(2000);
continue;
}
//输出结果
if(strcmp(reply->element[0]->str,"subscribe") != 0)
{
printf("%s",
reply->element[0]->st);//结果
printf("获取channel=》%s :%s",
reply->element[1]->str, //channel
reply->element[2]->str);//结果
printf("获取channel=》%s :%s",
reply->element[1]->str, //channel
reply->element[2]->str);//结果
}
//释放redisCommand执行后返回的redisReply所占用的内存
freeReplyObject(reply);
Sleep(2000); 

}

#endif

return 0;

}

阅读全文
0 0
原创粉丝点击