使用 Paho MQTT 订阅消息时如何读取标头键:值对 [英] How to read header key:value pair when subscribing a message with Paho MQTT

查看:127
本文介绍了使用 Paho MQTT 订阅消息时如何读取标头键:值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 pika like 向我的 rabbitmq 代理发布消息时添加了一个标头键:值对

I am adding a header key:value pair when publishing a message to my rabbitmq broker using pika like

channel.basic_publish(exchange=self.exchange,
                      routing_key=self.routing_key,
                      properties=pika.BasicProperties(
                          headers={'key': 'value'} 
                      ),
                      body=message)

在我的客户端,我使用 websockets 订阅 Paho MQTT 的主题.如何使用 Paho MQTT 检索相同的消息标头.我尝试了以下对我不起作用的方法

On my client side I am subscribing the topic with Paho MQTT using websockets. How can I retrieve the same messages header using Paho MQTT . I have tried the following methods which doesn't work for me

def onMessage(client, userdata, message):

    print("topic: " + message.topic + ", message: " + str(message.payload, 'utf-8'))
    print(client.headers)
    print(userdata.headers)
    print(message.headers)

更新

我发现该消息具有属性"属性.但是当我尝试 print(message.properties) 时,它给出了 AttributeError: properties

推荐答案

Pika 是一个 AMQP 客户端,以 AMQP 格式发布消息.

Pika is a AMQP client publishing messages in AMQP format.

Paho 是一个 MQTT 客户端,因此只能处理该格式的消息.在 MQTT v3(Paho Python 客户端尚不支持 MQTT v5)中,该协议没有任何范围来保存消息属性.MQTT v3 消息的唯一属性是 topicpayloadQOSretained 位.

Paho is a MQTT client and as such can only handle messages in that format. At MQTT v3 (the Paho Python client does not support MQTT v5 yet) the protocol does not have any scope to hold message attributes. The only properties a MQTT v3 message has are topic, payload, QOS and a retained bit.

因此,在将消息从队列移动到 MQTT 主题之前,RabbitMQ 代理必须进行格式转换并剥离属性.

So the RabbitMQ broker must be doing a format conversion and stripping the attributes off before moving the message from the Queue to the MQTT Topic.

所以基本上我是说 MQTT 消息中没有要读取的属性.

So basically I'm saying there are no attributes in the MQTT message to read.

看起来最新版本的 Paho Python 客户端确实支持 MQTTv5(该文档尚未更新).虽然 MQTTv5v 确实支持标头中的键/值对属性,但这将取决于使用 MQTTv5 和 RabbitMQ 实际连接的客户端是否支持 MQTTv5 并将值复制到新格式.

It looks like the latest version of the Paho Python client does support MQTTv5 (the doc has just not been updated). While MQTTv5v does support Key/Value pair attributes in the header, it will depend on the client actually connecting using MQTTv5 and RabbitMQ supporting both MQTTv5 and copying the values over to the new format.

这篇关于使用 Paho MQTT 订阅消息时如何读取标头键:值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆