Redis 介绍
Redis发布/ 订阅系统 是 Web 系统中比较常用的一个功能。简单点说就是 发布者发布消息,订阅者接收消息,这有点类似于我们的报纸/ 杂志社之类的
实现代码
#ifndef MAINWIDGET_H
#define MAINWIDGET_H
#include <QWidget>
#include <QDebug>
#include "QtRedis.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWidget; }
QT_END_NAMESPACE
class MainWidget : public QWidget
{
Q_OBJECT
public:
MainWidget(QWidget *parent = nullptr);
~MainWidget();
signals:
private slots:
void onSlotReceiveSubscribe(QString type, QString channel, QString message);
void on_connRedisBtn_clicked();
void on_pushButton_subscribe_clicked();
void on_pushButton_publish_clicked();
void on_pushButton_Clear_clicked();
private:
Ui::MainWidget *ui;
CQtRedis *m_redis;
};
#endif // MAINWIDGET_H
cpp
#include "mainwidget.h"
#include "ui_mainwidget.h"
MainWidget::MainWidget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::MainWidget)
{
ui->setupUi(this);
setWindowTitle("Qt实现Redis发布订阅功能");
setFixedSize(570, 454);
ui->textEdit->setReadOnly(true);
ui->textEdit->setTextColor(Qt::red);
ui->textEdit->setFontFamily("Consolas");
ui->textEdit->setFontPointSize(14);
ui->addressLiEdit->setText("localhost");
ui->portLiEdit->setText("6379");
ui->textEdit->append("-----------Redis 订阅发布实时日志显示-----------");
m_redis = new CQtRedis(this);
connect(m_redis,&CQtRedis::sigNotifyMessage,this,&MainWidget::onSlotReceiveSubscribe);
}
MainWidget::~MainWidget()
{
delete ui;
}
void MainWidget::onSlotReceiveSubscribe(QString type, QString channel, QString message)
{
ui->textEdit->append(QString("接收到数据类型=【%1】, 频道=【%2】,消息=【%3】").arg(type).arg(channel).arg(message));
}
void MainWidget::on_connRedisBtn_clicked()
{
if("连接"==ui->connRedisBtn->text())
{
ui->connRedisBtn->setText("断开");
m_redis->connect(ui->addressLiEdit->text(),ui->portLiEdit->text().toInt());
}else{
ui->connRedisBtn->setText("连接");
m_redis->disConnect();
}
}
void MainWidget::on_pushButton_subscribe_clicked()
{
if("订阅频道" == ui->pushButton_subscribe->text())
{
m_redis->subscribe(ui->lineEdit_channel->text());
ui->pushButton_subscribe->setText("取消订阅");
}else{
m_redis->unsubscribe(ui->lineEdit_channel->text());
ui->pushButton_subscribe->setText("订阅频道");
}
}
void MainWidget::on_pushButton_publish_clicked()
{
m_redis->publish(ui->lineEdit_channel->text(), ui->lineEdit_message->text());
}
void MainWidget::on_pushButton_Clear_clicked()
{
ui->textEdit->clear();
}
Qt对redis 调用实现进行了封装
class CQtRedis : public QObject
{
Q_OBJECT
public:
explicit CQtRedis(QObject *parent=nullptr);
~CQtRedis();
//连接Redis服务器
bool connect(QString ip, int port);
//断开连接Redis服务器
bool disConnect();
//向redis指定的通道号发布消息
bool publish(QString channel, QString msg);
//向redis指定通道订阅消息
bool subscribe(QString channel);
//向redis指定通道取消订阅消息
bool unsubscribe(QString channel);
signals:
//通知订阅接收到的消息
void sigNotifyMessage(QString type, QString channel, QString message);
private:
void notifySubscibeMessage(QString type, QString channel, QString message);
工程下载连接
https://download.csdn.net/download/ZuoYueXian/89446204