ZBLOG

Redis订阅多个主题

在Redis中,可以通过使用多个SUBSCRIBE命令来同时订阅多个主题(频道)的消息。以下是一个示例代码演示如何实现:

#include <iostream>
#include <string>
#include <vector>
#include <hiredis/hiredis.h>

void subscribeToChannels(const std::vector<std::string>& channels)
{
    // 创建 Redis 连接
    redisContext* redis = redisConnect("localhost", 6379);
    if (redis == nullptr || redis->err) {
        std::cerr << "Failed to connect to Redis: " << redis->errstr << std::endl;
        return;
    }

    // 构建 SUBSCRIBE 命令字符串
    std::string subscribeCommand = "SUBSCRIBE";
    for (const auto& channel : channels) {
        subscribeCommand += " " + channel;
    }

    // 使用 SUBSCRIBE 命令订阅多个主题
    redisReply* reply = static_cast<redisReply*>(redisCommand(redis, subscribeCommand.c_str()));
    if (reply == nullptr || reply->type != REDIS_REPLY_ARRAY) {
        std::cerr << "Failed to execute SUBSCRIBE command: " << redis->errstr << std::endl;
        return;
    }

    // 循环监听消息
    while (true) {
        if (redisGetReply(redis, reinterpret_cast<void**>(&reply)) != REDIS_OK) {
            break;  // 订阅被取消或出错时退出循环
        }
        
        if (reply->type == REDIS_REPLY_ARRAY && reply->elements >= 3) {
            std::string messageType(reply->element[0]->str);
            
            // 处理不同类型的消息
            if (messageType == "message") {
                std::string channelName(reply->element[1]->str);
                std::string messageContent(reply->element[2]->str);
                
                std::cout << "Received message from channel [" << channelName << "]: " << messageContent << std::endl;
            } else if (messageType == "subscribe") {
                std::string channelName(reply->element[1]->str);
                std::cout << "Subscribed to channel: " << channelName << std::endl;
            }
        }
        
        // 释放回复对象
        freeReplyObject(reply);
    }

    // 关闭连接
    redisFree(redis);
}

int main()
{
    // 要订阅的频道列表
    std::vector<std::string> channels = { "channel1", "channel2", "channel3" };
    
    // 订阅多个主题并接收消息
    subscribeToChannels(channels);

    return 0;
}

以上代码中,通过在SUBSCRIBE命令中列出要订阅的频道,可以同时订阅多个主题。在消息处理部分,根据需要进行不同频道的区分和处理。

希望对你有所帮助!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=11723

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?