ZBLOG

Redis能订阅消息吗

是的,Redis支持发布/订阅模式。通过使用Redis的PUB/SUB功能,你可以实现消息的发布和订阅。

以下是一个示例代码,演示如何在Redis中进行消息发布和订阅:

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

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

    // 使用 SUBSCRIBE 命令订阅指定频道的消息
    redisReply* reply = static_cast<redisReply*>(redisCommand(redis, "SUBSCRIBE %s", channel.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);
}

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

    // 使用 PUBLISH 命令发布消息到指定频道
    redisReply* reply = static_cast<redisReply*>(redisCommand(redis, "PUBLISH %s %s", channel.c_str(), message.c_str()));
    if (reply == nullptr) {
        std::cerr << "Failed to execute PUBLISH command: " << redis->errstr << std::endl;
        return;
    }

    // 检查命令执行结果
    if (reply->type != REDIS_REPLY_INTEGER || reply->integer < 0) {
        std::cerr << "Failed to publish message" << std::endl;
    } else {
        std::cout << "Published message to channel [" << channel << "]"<<std::endl;
    }

    // 释放回复对象并关闭连接
    freeReplyObject(reply);
    
    // 关闭连接
    redisFree(redis);
}

int main()
{
    std::string channel = "my_channel";
    
    // 订阅频道并接收消息
    subscribeToChannel(channel);

    // 发布消息到频道
    publishToChannel(channel, "Hello, Redis!");

    return 0;
}

以上代码演示了如何在Redis中订阅指定频道的消息,并通过PUBLISH命令发布消息到指定频道。你可以根据需要自定义频道名和消息内容,并使用相关库(如hiredis)来实现与Redis的通信。请注意,该示例中的订阅是一个阻塞操作,程序会一直等待新的消息到达。如果想要取消订阅,可以在另一个线程或进程中执行UNSUBSCRIBE命令。

希望以上信息对你有所帮助!


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?