Regulator 简介

更新时间:
2024-02-20
下载文档

Regulator 简介

QVSOA Regulator 为微服务开发提供了变速器功能,本节将指导您如何使用 QVSOA Regulator。

开发须知

在许多场景中,我们需要控制发布频率。例如,一个 UI 界面不能接收过多的数据更新频率,但是此时发布者的发布频率可能非常快。在这种场景下,我们需要改变发布的频率。

使用 QVSOA Regulator 可以解决这个问题,它既可以使用在服务端,也可以使用在客户端。

本文中使用的客户端对应 发布与订阅 章节的服务端例程

开发示例

#include <QCoreApplication>
#include <QDebug>
#include <QVsoa>

constexpr char SERVER_PASSWORD[] = "123456";

using namespace std::placeholders;

void onConnected(bool ok, QString info)
{
    if (!ok) {
        qDebug() << "Connected with server failed!";
        return;
    }
    qDebug() << "Connected with server:" << info;
}

void onDisconnected()
{
    qDebug() << "Connection break";
}

void onMessage(QVsoaRegulator *regulator, QString url, QVsoaPayload payload)
{
    regulator->update(url, payload);
}

void ondelay(const QString &url, const QVsoaPayload &payload)
{
    qDebug() << "received event:" << url << "payload:" << payload.param();
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // Initilize client
    QVsoaClient client;
    if (client.isInvalid()) {
        qDebug() << "Can not create VSOA client!";
        return -1;
    }

    // Initilize regulator
    QVsoaRegulator regulator(3000);
    // Add slot with 1024 bytes buffer.
    regulator.addSlot("/axis", ondelay, 1024);

    QObject::connect(&client, &QVsoaClient::connected, onConnected);
    QObject::connect(&client, &QVsoaClient::disconnected, onDisconnected);
    QObject::connect(&client, &QVsoaClient::message, std::bind(onMessage, &regulator, _1, _2));

    // Connect to server with password
    client.connect2server("vsoa://axis_server", SERVER_PASSWORD, 1000);
    // Enable automatic connections
    client.autoConnect(1000, 500);
    // Subscribe /axis
    client.subscribe("/axis");
    // Enable data consistency on /axis
    client.autoConsistent({"/axis"}, 1000);

    return a.exec();
}
文档内容是否对您有所帮助?
有帮助
没帮助