Publish Messages to an MQTT Broker with MQTT Connector
In the following example, you configure the Anypoint Connector for MQTT (MQTT Connector) Publish operation, which enables you to publish a message to the desired topic and with a specific quality of service (QoS).
-
In Studio > Mule Palette, select HTTP > Listener.
-
Drag Listener to the Studio canvas.
-
Set Path to
/mqtt3/publish
. -
Click the plus sign (+) next to the Connector configuration field to configure a global element that can be used by all instances of the source in the app.
-
Configure the HTTP Listener global element and click OK.
-
In Studio > Mule Palette, select MQTT3 > On New Message.
-
Drag On New Message to the Studio canvas.
-
In the On New Message configuration screen, optionally change the value of the Display Name field.
-
Click the plus sign (+) next to the Connector configuration field to configure a global element that can be used by all instances of the source in the app.
-
In MQTT3 Config > Connection, select MQTT3 URL Connection.
-
For Client id generator, select Client id random suffix generator.
-
Set the following fields:
-
Client ID:
smart-bentley-123
-
Username:
usertest
-
Password:
passtest
-
URL:
tcp://127.0.0.1:1883
-
-
Click OK.
-
In the Publish configuration screen, set the following fields:
-
Topic:
quotes/terryPratchett
-
Message
#["Stories of imagination tend to upset those without one."]
-
QoS: AT_LEAST_ONCE (Default)
-
Is retained: True
-
In the Configuration XML editor, the <mqtt3:publish>
and topic
configurations look like this:
<mqtt3:config name="MQTT_Config">
<mqtt3:connection username="usertest" password="passtest" url="tcp://127.0.0.1:1883">
<mqtt3:client-id-generator>
<mqtt3:client-id-random-suffix-generator clientId="smart-bentley-123" />
</mqtt3:client-id-generator>
</mqtt3:connection>
</mqtt3:config>
<flow name="publishQuote">
<http:listener config-ref="HTTP_Listener" path="/mqtt3/publish" />
<mqtt3:publish config-ref="MQTT_Config" topic="quotes/terryPratchett" qos="AT_LEAST_ONCE" isRetained="true">
<mqtt3:message>#["Stories of imagination sample quote."]</mqtt3:message>
</mqtt3:publish>
</flow>
Mark Messages as Retained
By default, a broker discards a received message on a topic for which there are no current subscribers. If you want the broker to retain the message, configure Is retained to True
. The broker stores the last retained message and the corresponding quality of service for the selected topic.
Each client that subscribes to a topic pattern that matches the topic of the retained message receives the retained message after they subscribe. The broker stores only one retained message per topic. This enables new subscribers to receive the most current existing value rather than waiting for the next update from a publisher.