MQTT介绍和最佳实践

与一般的消息队列相比,MQTT的主题是相当轻量。客户端在发布或者订阅主题前,不需要事先创建。代理不需要任何初始化,接收每一个主题。主题是一种地址组织方式,这种组织方式
允许客户端间交互信息。MQTT以一种文件系统的方式进行组织,这样就可以创建可以自我描述和用户友好主题。
主题有以下特点:
1、大小写敏感
2、UTF-8编码
3、至少包含一个字符
除了$SYS主题外,没有其他默认或者标准的主题。代理只默认创建$SYS主题,不创建其他任何主题。所有主题都是由,客户端通过订阅或者发布创建,并且不永久的。
一个主题存在的条件:存在客户端订阅或者代理存储有这个主题保留值。
代理用$SYS主题,发布自身信息。
订阅主题
一个客户可以订阅一个或者多个主题。
订阅多个主题时,可以采用通配符:#:多级通配符;+:单级通配符。
主题何时被创建
1、订阅某个主题时;
2、发布了一个允许保留值的主题时。
何时主题被从代理中移除:
1、当最后个订阅者与Broker断开连接,并且清除事务设置为真;
2、当一个设置清除事务设置为真的客户端连接时。

最佳实践
1、主题不要以/开头
以/开头的主题在MQTT中被允许,但允许用并不一定要必须用。然而如果以/开头就引入以0个字符顶级主题,这样除了造成混乱外,不会带来其他好处。
2、主题中不能有空格
空格是开发人员自然而然想避免的字符。带空格的主题会造成调试困难。
3、主题要精简
4、最好只有ASCII码;
5、在主题中带上客户端的标识;
6、不要订阅全部主题。
订阅所有主题,会带很大的网络流量,单个客户端也可能处理不过来。

 

Understanding MQTT Topics

https://www.hivemq.com/blog/mqtt-essentials-part-8-retained-messages/

In comparison to a message queue, MQTT topics are very lightweight. The client does not need to create the desired topic before they publish or subscribe to it. The broker accepts each valid topic without any prior initialization.

MQTT topics are a form of addressing that allows MQTT clients to share information.

MQTT Topics are structured in a hierarchy similar to folders and files in a file system using the forward slash ( / )as a delimiter.

Using this system you can create a user friendly and self descriptive naming structures of you own choosing.

Topic names are:

  • Case sensitive
  • use UTF-8 strings.
  • Must consist of at least one character to be valid.

 

Except for the $SYS topic there is no default or standard topic structure.

That is there are no topics created on a broker by default, except for the $SYS topic.

All topics are created by a subscribing or publishing client, and they are not permanent.

A topic only exists if a client has subscribed to it, or a broker has a retained or last will messages stored for that topic.

The $SYS topic

This is a reserved topic and is used by most MQTT brokers to publish information about the broker.

They are read-only topics for the MQTT clients. There is no standard for this topic structure but there is a guideline here that most broker implementations seem to follow.

Here is a Mosquitto dashboard that displays data published over the $SYS topic by mosquitto. The code is here.

Subscribing to Topics

A client can subscribe to individual or multiple topics.

When subscribing to multiple topics two wildcard characters can be used. They are:

  • # (hash character) – multi level wildcard
  • + (plus character) -single level wildcard

Wildcards can only be used to denote a level or multi-levels i.e /house/# and not as part of the name to denote multiple characters e.g. hou# is not valid

Topic naming Examples:

Valid Topic subscriptions

Single topic subscriptions

  • /
  • /house
  • house/room/main-light
  • house/room/side-light

Using Wildcards

Subscribing to topic house/#

Covers

  • house/room1/main-light
  • house/room1/alarm
  • house/garage/main-light
  • house/main-door
  • etc

Subscribing to topic house/+/main-light

covers

  • house/room1/main-light
  • house/room2/main-light
  • house/garage/main-light

but doesn’t cover

  • house/room1/side-light
  • house/room2/side-light

Invalid Topic Subscriptions

  • house+ – Reason- no topic level
  • house# – Reason- no topic level

Publishing to Topics

A client can only publish to an individual topic. That is, using wildcards when publishing is not allowed.

E.G- To publish a message to two topics you need to publish the message twice

When are Topics Created

Topics are created dynamically when:

  • Someone subscribes to a topic
  • Someone publishes a message to a topic with the retained message set to True.

When are Topics Removed from a Broker

  • When the last client that is subscribing to that broker disconnects, and clean session is true.
  • When a client connects with clean session set to True.

Republishing Topic Data

This is likely to be done when changing or combining naming schemes.

The idea is that a client would subscribe to a topic, e.g.

hub1/sensor1 and republish the data using a new topic naming of house1/main-light.

Video A Beginners Guide to MQTT Topics

Common Questions and Answers

Q- How do I subscribe to all topics?

A-Subscribe to #

Q- How Do I subscribe to all $SYS topics?

A-Subscribe to $SYS/#

Q- Should I start my Topic hierarchy with a /.

A- It is not necessary and just adds another level to the structure.

Q- Can I get list of all topics on a broker?

A- Not unless you subscribe to all topics and scan them.

Q- Can I tell who is subscribed to a topic?

A– No

Q- How do I discover topics?

A- There is currently no mechanism for that except as described in list all topics.

 

 

Best practices

Never use a leading forward slash

A leading forward slash is permitted in MQTT. For example, /myhome/groundfloor/livingroom. However, the leading forward slash introduces an unnecessary topic level with a zero character at the front. The zero does not provide any benefit and often leads to confusion.

Never use spaces in a topic

A space is the natural enemy of every programmer. When things are not going the way they should, spaces make it much harder to read and debug topics. As with leading forward slashes, just because something is allowed, doesn’t mean it should be used. UTF-8 has many different white space types, such uncommon characters should be avoided.

Keep the topic short and concise

Each topic is included in every message in which it is used. Make your topics as short and concise as possible. When it comes to small devices, every byte counts and topic length has a big impact.

Use only ASCII characters, avoid non printable characters

Because non-ASCII UTF-8 characters often display incorrectly, it is very difficult to find typos or issues related to the character set. Unless it is absolutely necessary, we recommend avoiding the use of non-ASCII characters in a topic.

Embed a unique identifier or the Client Id into the topic

It can be very helpful to include the unique identifier of the publishing client in the topic. The unique identifier in the topic helps you identify who sent the message. The embedded ID can be used to enforce authorization. Only a client that has the same client ID as the ID in the topic is allowed to publish to that topic. For example, a client with the _client1 ID is allowed to publish to _client1/status, but not permitted to publish to _client2/status.

Don’t subscribe to #

Sometimes, it is necessary to subscribe to all messages that are transferred over the broker. For example, to persist all messages into a database. Do not subscribe to all messages on a broker by using an MQTT client and subscribing to a multi-level wildcard. Frequently, the subscribing client is not able to process the load of messages that results from this method (especially if you have a massive throughput). Our recommendation is to implement an extension in the MQTT broker. For example, with the plugin system of HiveMQ you can hook into the behavior of HiveMQ and add an asynchronous routine to process each incoming message and persist it to a database.

Don’t forget extensibility

Topics are a flexible concept and there is no need to preallocate them in any way. However, both the publisher and the subscriber need to be aware of the topic. It is important to think about how topics can be extended to allow for new features or products. For example, if your smart-home solution adds new sensors, it should be possible to add these to your topic tree without changing the whole topic hierarchy.

Use specific topics, not general ones

When you name topics, don’t use them in the same way as in a queue. Be as specific topics as possible. For example, if you have three sensors in your living room, create topics for _myhome/livingroom/temperature, _myhome/livingroom/brightness and _myhome/livingroom/humidity. Do not send all values over _myhome/livingroom. Use of a single topic for all messages is a anti pattern. Specific naming also makes it possible for you to use other MQTT features such as retained m

 

 

Welcome to the eighth part of MQTT Essentials. A ten-part blog series on the core features and concepts of the MQTT protocol. This post introduces retained messages.

In MQTT, the client that publishes a message has no guarantee that a subscribing client actually receives the message. The publishing client can only make sure that the message gets delivered safely to the broker. Basically, the same is true for a subscribing client. The client that connects and subscribes to topics has no guarantee on when the publishing client will publish a message in one of their topics of interest. It can take a few seconds, minutes, or hours for the publisher to send a new message in one of the subscribed topics. Until the next message is published, the subscribing client is totally in the dark about the current status of the topic. This situation is where retained messages come into play.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值