是的,你可以使用Lambda表达式来实现在接收数据的线程中调用类中的函数。下面是一个示例代码:
#include <QCoreApplication>
#include <QObject>
#include <QDebug>
#include <hiredis/hiredis.h>
class RedisSubscriber : public QObject
{
Q_OBJECT
public:
explicit RedisSubscriber(QObject* parent = nullptr)
: QObject(parent) {}
void processData(const QString& channel, const QString& data)
{
// 在这里处理接收到的消息
qDebug() << "Received message on channel" << channel << ":" << data;
}
public slots:
void run()
{
redisContext* context = redisConnect("localhost", 6379);
if (context != nullptr && context->err == 0)
{
redisReply* reply = static_cast<redisReply*>(redisCommand(context, "SUBSCRIBE channel_name"));
if (reply != nullptr && reply->type == REDIS_REPLY_ARRAY && reply->elements >= 3)
{
while (true)
{
redisReply* message = nullptr;
if (redisGetReply(context, reinterpret_cast<void**>(&message)) == REDIS_OK)
{
if (message != nullptr && message->type == REDIS_REPLY_ARRAY && message->elements >= 3)
{
QString channel = message->element[1]->str;
QString data = message->element[2]->str;
// 在Lambda表达式中调用类中的函数处理接收到的消息
QCoreApplication::postEvent(this, [this, channel, data](){
processData(channel, data);
});
}
freeReplyObject(message);
}
}
}
freeReplyObject(reply);
}
redisFree(context);
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
RedisSubscriber subscriber;
QThread thread;
QObject::connect(&thread, &QThread::started, &subscriber, &RedisSubscriber::run);
subscriber.moveToThread(&thread);
thread.start();
return a.exec();
}
#include "main.moc"
在上述代码中,通过使用QCoreApplication::postEvent()函数在接收到消息后,在主线程中调用Lambda表达式来调用processData()函数处理接收到的消息。
请注意,为了使Lambda表达式能够访问类中的成员函数,我们需要将RedisSubscriber对象移到新线程,并确保该对象在该线程内执行。另外,因为使用了QObject子类的信号槽机制,我们还需要对.moc文件进行编译处理。
希望这可以帮助你实现在Qt中使用Redis发布与订阅并在接收数据的模块开启一个线程循环等待数据。
内容由零声教学AI助手提供,问题来源于学员提问




