1. 程式人生 > >windows c++使用hiredis同步模式實現釋出訂閱

windows c++使用hiredis同步模式實現釋出訂閱

//參考網址

     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;

}