以下是一个简单的示例伪代码,演示如何监听五个Redis队列:
#include <iostream>
#include <thread>
#include <hiredis/hiredis.h>
void listenToQueue(const std::string& queueName) {
redisContext* context = redisConnect("127.0.0.1", 6379); // 连接到Redis服务器
if (context == nullptr || context->err) {
std::cerr << "Failed to connect to Redis: " << (context ? context->errstr : "nullptr") << std::endl;
return;
}
// 订阅指定的队列
redisReply* reply = static_cast<redisReply*>(redisCommand(context, "SUBSCRIBE %s", queueName.c_str()));
freeReplyObject(reply);
while (true) {
// 阻塞等待消息
redisReply* message;
if (redisGetReply(context, reinterpret_cast<void**>(&message)) == REDIS_OK) {
if (message->type == REDIS_REPLY_ARRAY && message->elements >= 3) {
std::string receivedQueueName = message->element[1]->str;
std::string data = message->element[2]->str;
// 处理接收到的消息
std::cout << "Received from queue [" << receivedQueueName << "]: " << data << std::endl;
// TODO: 根据业务需求进行相应处理
if (data == "quit") {
break; // 如果接收到特定消息(例如"quit"),退出循环并停止监听
}
}
}
freeReplyObject(message);
}
redisFree(context); // 断开与Redis服务器的连接
}
int main() {
// 创建并启动五个线程,分别监听五个Redis队列
std::thread thread1(listenToQueue, "queue1");
std::thread thread2(listenToQueue, "queue2");
std::thread thread3(listenToQueue, "queue3");
std::thread thread4(listenToQueue, "queue4");
std::thread thread5(listenToQueue, "queue5");
// 主线程等待所有子线程结束
thread1.join();
thread2.join();
thread3.join();
thread4.join();
thread5.join();
return 0;
}
请注意,上述示例代码仅为演示目的,并未考虑错误处理、优雅退出等方面的完整性。实际使用时,请根据你的需求进行适当调整和扩展。
内容由零声教学AI助手提供,问题来源于学员提问