44 lines
1.4 KiB
C++
44 lines
1.4 KiB
C++
#include <hiredis/hiredis.h>
|
|
#include <iostream>
|
|
#include <cstring> // 必须包含此头文件
|
|
|
|
void subscribe_thread() {
|
|
redisContext *c = redisConnect("127.0.0.1", 9090);
|
|
if (c == nullptr || c->err) {
|
|
std::cerr << "连接失败: " << (c ? c->errstr : "无上下文") << std::endl;
|
|
return;
|
|
}
|
|
|
|
// 订阅所有键空间事件
|
|
//PSUBSCRIBE __keyspace@0__:* 通配符*表示所有键空间事件
|
|
redisReply *reply = (redisReply *)redisCommand(c, "PSUBSCRIBE __keyspace@0__:*");
|
|
if (reply == nullptr || c->err) {
|
|
std::cerr << "订阅失败: " << c->errstr << std::endl;
|
|
freeReplyObject(reply);
|
|
redisFree(c);
|
|
return;
|
|
}
|
|
freeReplyObject(reply);
|
|
|
|
while (true) {
|
|
redisReply *msg_reply = nullptr;
|
|
if (redisGetReply(c, (void **)&msg_reply) != REDIS_OK) {
|
|
std::cerr << "接收消息错误" << std::endl;
|
|
break;
|
|
}
|
|
|
|
if (msg_reply && msg_reply->type == REDIS_REPLY_ARRAY
|
|
&& msg_reply->elements >= 3
|
|
&& strcmp(msg_reply->element[0]->str, "pmessage") == 0) {
|
|
std::cout << "事件频道: " << msg_reply->element[2]->str
|
|
<< ",操作类型: " << msg_reply->element[3]->str << std::endl;
|
|
}
|
|
freeReplyObject(msg_reply);
|
|
}
|
|
redisFree(c);
|
|
}
|
|
|
|
int main() {
|
|
subscribe_thread();
|
|
return 0;
|
|
} |