ZBLOG

Qt使用redis写一个订阅发布的小demo

下面是一个使用Qt和Redis实现订阅发布功能的小demo代码:

#include <iostream>
#include <QObject>
#include <QCoreApplication>
#include <hiredis/hiredis.h>

class RedisClient : public QObject {
    Q_OBJECT

public:
    RedisClient(QObject *parent = nullptr) : QObject(parent) {}

public slots:
    void subscribe(const QString &channel) {
        redisContext *ctx = redisConnect("localhost", 6379);
        if (ctx == nullptr || ctx->err) {
            if (ctx) {
                std::cout << "Error: " << ctx->errstr << std::endl;
                redisFree(ctx);
            } else {
                std::cout << "Can't allocate redis context" << std::endl;
            }
            return;
        }

        redisReply *reply = static_cast<redisReply *>(redisCommand(ctx, "SUBSCRIBE %s", channel.toStdString().c_str()));
        freeReplyObject(reply);

        while (true) {
            redisReply *reply = nullptr;
            if (redisGetReply(ctx, reinterpret_cast<void **>(&reply)) == REDIS_OK && reply != nullptr) {
                if (reply->type == REDIS_REPLY_ARRAY && reply->elements >= 3 && strcmp(reply->element[0]->str, "message") == 0) {
                    QString receivedChannel(reply->element[1]->str);
                    QString message(reply->element[2]->str);
                    emit messageReceived(receivedChannel, message);
                }
                freeReplyObject(reply);
            }
        }

        redisFree(ctx);
    }

signals:
    void messageReceived(const QString &channel, const QString &message);
};

int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);

    RedisClient client;

    QObject::connect(&client, &RedisClient::messageReceived, [&](const QString &channel, const QString &message) {
        std::cout << "Received message on channel " << channel.toStdString() << ": " << message.toStdString() << std::endl;
    });

    // 订阅频道
    client.subscribe("test_channel");

    return app.exec();
}

#include "main.moc"

上述代码使用了hiredis库进行与Redis的交互。在RedisClient类中,通过调用subscribe槽函数订阅指定的频道。当接收到订阅频道上的消息时,会通过信号messageReceived发出。

main()函数中,创建一个RedisClient对象,并连接其messageReceived信号到一个Lambda表达式,以输出接收到的消息。最后调用客户端对象的subscribe()函数开始订阅。

请确保已经正确安装hiredis库,并在编译时链接该库。此外,请将Redis服务器地址和端口根据实际情况进行修改。

希望以上代码对您有所帮助!


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?