下面是一个使用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助手提供,问题来源于学员提问




