ZBLOG

#include 实现订阅发布的Qt版本写法

在Qt中使用 hiredis 库实现订阅发布的写法如下:

首先,确保已经安装了 hiredis 库并在项目配置文件中添加对应的链接。然后,可以通过以下代码来实现订阅和发布功能:

#include <QCoreApplication>
#include <QDebug>
#include <hiredis/hiredis.h>

// 订阅回调函数
void subscribeCallback(redisAsyncContext *c, void *, void *reply) {
    redisReply *r = (redisReply*)reply;
    if (r == nullptr) {
        qDebug() << "Failed to receive message";
        return;
    }
    
    // 处理接收到的消息
    if (r->type == REDIS_REPLY_ARRAY && r->elements == 3) {
        QString type = QString::fromUtf8(r->element[0]->str);
        QString channel = QString::fromUtf8(r->element[1]->str);
        QString message = QString::fromUtf8(r->element[2]->str);
        
        qDebug() << "Received message:";
        qDebug() << "Type: " << type;
        qDebug() << "Channel: " << channel;
        qDebug() << "Message: " << message;
    }
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    
    // 创建异步上下文
    redisAsyncContext *context = redisAsyncConnect("127.0.0.1", 6379);
    
    if (context->err) {
        qDebug() << "Error connecting to Redis server: " << context->errstr;
        return 1;
    }
    
    // 设置订阅回调函数
    redisLibeventAttach(context, QCoreApplication::instance()->eventDispatcher()->base());
    redisAsyncSetConnectCallback(context, [](const redisAsyncContext *c, int status) {
        if (status != REDIS_OK) {
            qDebug() << "Error connecting to Redis server: " << c->errstr;
            return;
        }
        
        qDebug() << "Connected to Redis server";
        
        // 发布消息
        const char *channel = "channel";
        const char *message = "Hello, world!";
        redisAsyncCommand(context, nullptr, nullptr, "PUBLISH %s %s", channel, message);
    });
    
    // 订阅频道
    const char *channel = "channel";
    redisAsyncCommand(context, subscribeCallback, nullptr, "SUBSCRIBE %s", channel);
    
    return a.exec();
}

在上述代码中,首先创建了一个异步上下文 redisAsyncContext,然后通过调用 redisAsyncConnect() 连接到 Redis 服务器。连接成功后,设置了连接回调函数,并使用 redisAsyncCommand() 来发布和订阅消息。

请注意,这只是一个简单的示例,你可能需要根据实际需求进行进一步的修改和扩展。同时,请确保已经正确地链接 hiredis 库,并根据实际情况修改连接信息(如 IP 地址、端口号等)。

希望这能帮助到你!如果还有其他问题,请随时提问。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?