如何在HiveMQ客户端中获取客户端的QoS?

时间:2019-07-19 16:22:56

标签: java mqtt iot hivemq

我正在使用HiveMQ客户端,我想知道是否有一种方法可以获取客户端订阅的服务质量(QoS)(就特定主题而言还是一般而言)?我会寻找一种可以像这样在客户端上调用的方法:

    Mqtt5BlockingClient subscriber = Mqtt5Client.builder()
            .identifier(UUID.randomUUID().toString()) // the unique identifier of the MQTT client
            .serverHost("localhost") 
            .serverPort(1883) 
            .buildBlocking();

subscriber.getQoS("topic") // returns the QoS of the subscriber is subscribing to the given topic 

我只需要这些信息,以便可以打印到控制台中。

1 个答案:

答案 0 :(得分:2)

我认为您必须阅读有关MQTT概念的更多信息。 服务质量(QoS)级别是消息的发送者和接收者之间关于保证传递消息的协议。 因此,publish()subscribe()方法中使用的是QoS,而不是connect()中使用的。

这是场景:

1。连接:
您必须将客户端连接到使用用户名/密码的任何代理。每个mqtt库都有一个connect()方法。在此步骤中,您尚未指定qos。
成功连接后(每个mqtt库都有一个connect方法的回调),您可以发布或订阅任何想要的(或允许的)主题。
示例:
Eclipse Paho library:

IMqttToken token = clientPhone.connect();

HiveMQ Library:

client.connect();
//or
client.connectWith().keepAlive(10).send(); 
//or
Mqtt5Connect connectMessage = Mqtt5Connect.builder().keepAlive(10).build();
client.connect(connectMessage);

2。发布:
当您想要publish()一条消息时,必须指定一个服务质量,以便代理将根据以下服务质量来响应客户端:

Qos=0:
Client  ---- Publish method ----> broker
Qos=1:
Client  ---- Publish method  ----> broker
Client <---- PubAck callback ----  broker
Qos=2:
Client  ---- Publish method   ----> broker
Client <---- PubRec callback  ----  broker
Client  ---- PubRel method    ----> broker
Client <---- PubComp callback ----  broker

示例:

Eclipse Paho library:

IMqttDeliveryToken tokenPub = clientPhone.publish(topicPub, message);

HiveMQ Library:

client.publishWith()
        .topic("test/topic")
        .qos(MqttQos.AT_LEAST_ONCE)
        .payload("payload".getBytes())
        .send();
//or:
Mqtt5Publish publishMessage = Mqtt5Publish.builder()
        .topic("test/topic")
        .qos(MqttQos.AT_LEAST_ONCE)
        .payload("payload".getBytes())
        .build();
client.publish(publishMessage);

3。订阅:
SUBSCRIBE消息可以包含任意数量的客户端订阅。每个订阅都是一对主题和QoS级别。订阅消息中的主题还可以包含通配符,这使得可以订阅某些主题模式。如果一个客户端的订阅重叠,则该主题的最高QoS级别将获胜,并且将由代理用于传递消息。
示例:

Eclipse Paho library:

IMqttToken subToken = MqttAndroidClientInstance.subscribe(topics, qos);

HiveMQ Library:

client.subscribeWith().topicFilter("test/topic").qos(MqttQos.EXACTLY_ONCE).send();
//or:
Mqtt5Subscribe subscribeMessage = Mqtt5Subscribe.builder()
        .topicFilter("test/topic")
        .qos(MqttQos.EXACTLY_ONCE)
        .build();
client.subscribe(subscribeMessage);

编辑(1):
如果要在重新连接后接收已订阅的主题,则mqtt客户端必须使用以下参数:
A- cleanSession false 连接。
B-订阅 QOS> 0