以下是一个简单的 Redis 类的 Qt 版本实现,包含订阅和发布功能:
#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;
}
}
class RedisClient : public QObject
{
Q_OBJECT
public:
explicit RedisClient(QObject *parent = nullptr)
: QObject(parent)
{
// 创建异步上下文
m_context = redisAsyncConnect("127.0.0.1", 6379);
if (m_context->err) {
qDebug() << "Error connecting to Redis server: " << m_context->errstr;
return;
}
// 设置连接回调函数
redisLibeventAttach(m_context, QCoreApplication::instance()->eventDispatcher()->base());
redisAsyncSetConnectCallback(m_context, [](const redisAsyncContext *c, int status) {
if (status != REDIS_OK) {
qDebug() << "Error connecting to Redis server: " << c->errstr;
return;
}
qDebug() << "Connected to Redis server";
});
}
~RedisClient()
{
if (m_context) {
redisAsyncDisconnect(m_context);
m_context = nullptr;
}
}
void publish(const QString& channel, const QString& message)
{
if (m_context) {
QByteArray channelData = channel.toUtf8();
QByteArray messageData = message.toUtf8();
redisAsyncCommand(m_context, nullptr, nullptr,
"PUBLISH %s %s", channelData.constData(), messageData.constData());
}
}
void subscribe(const QString& channel)
{
if (m_context) {
QByteArray channelData = channel.toUtf8();
redisAsyncCommand(m_context, subscribeCallback, nullptr,
"SUBSCRIBE %s", channelData.constData());
}
}
private:
redisAsyncContext *m_context = nullptr;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
RedisClient client;
// 发布消息
client.publish("channel", "Hello, world!");
// 订阅频道
client.subscribe("channel");
return a.exec();
}
#include "main.moc"
在这个实现中,我们创建了一个 RedisClient
类来处理与 Redis 服务器的连接和操作。它包含了发布和订阅的方法。在构造函数中,我们创建异步上下文,并设置连接回调函数。在析构函数中,我们断开与 Redis 的连接。
你可以根据需要进一步扩展和修改该类。记得根据实际情况修改连接信息(如 IP 地址、端口号等)。
希望对你有所帮助!如果还有其他问题,请随时提问。
内容由零声教学AI助手提供,问题来源于学员提问