下面是一个使用Qt实现Redis的订阅和发布功能的简单示例代码:
#include <QtCore/QCoreApplication>
#include <QDebug>
#include <QTimer>
#include <QTcpSocket>
class RedisClient : public QObject
{
Q_OBJECT
public:
explicit RedisClient(QObject *parent = nullptr)
: QObject(parent)
{
connect(&m_socket, &QTcpSocket::readyRead, this, &RedisClient::onReadyRead);
connect(&m_socket, &QTcpSocket::connected, this, &RedisClient::onConnected);
}
void connectToServer(const QString& host = "localhost", int port = 6379)
{
m_socket.connectToHost(host, port);
}
void subscribe(const QString& channel)
{
sendCommand(QString("SUBSCRIBE %1").arg(channel));
}
void publish(const QString& channel, const QString& message)
{
sendCommand(QString("PUBLISH %1 %2").arg(channel).arg(message));
}
signals:
void messageReceived(const QString& channel, const QString& message);
private slots:
void onConnected()
{
qDebug() << "Connected to Redis server.";
}
void onReadyRead()
{
QByteArray data = m_socket.readAll();
// 解析收到的消息,根据协议规则处理不同类型的回复
QList<QByteArray> replies = data.split('\n');
for (int i = 0; i < replies.size(); i += 4) {
if (replies.at(i) == "message") {
QString channel = QString::fromUtf8(replies.at(i+1));
QString message = QString::fromUtf8(replies.at(i+2));
emit messageReceived(channel, message);
}
}
}
private:
void sendCommand(const QString& command)
{
QByteArray data = QString("*1\r\n$%1\r\n%2\r\n").arg(command.size()).arg(command).toUtf8();
m_socket.write(data);
}
private:
QTcpSocket m_socket;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
RedisClient redis;
QObject::connect(&redis, &RedisClient::messageReceived, [](const QString& channel, const QString& message) {
qDebug() << "Received message from" << channel << ":" << message;
});
redis.connectToServer();
// 订阅频道
redis.subscribe("channel");
// 模拟发布消息
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, [&redis]() {
static int count = 0;
QString message = QString("Message %1").arg(count++);
redis.publish("channel", message);
qDebug() << "Published:" << message;
});
timer.start(1000);
return a.exec();
}
#include "main.moc"
这个示例使用QTcpSocket来与Redis服务器进行通信,并根据Redis协议规则解析收到的回复。你可以在main函数中订阅频道和发布消息。当接收到消息时,会发出messageReceived信号,你可以连接该信号并处理收到的消息。
请注意,这只是一个简单的示例,并没有考虑所有的异常情况和错误处理。在实际应用中,你可能需要更加完善和健壮的实现。
内容由零声教学AI助手提供,问题来源于学员提问




