Save offline messages to MongoDB

Set up the MongoDB database and set the user name and password to root/public. Take MacOS X as an example:

  1. $ brew install mongodb
  2. $ brew services start mongodb
  3. ## Add root/public user
  4. $ use mqtt;
  5. $ db.createUser({user: "root", pwd: "public", roles: [{role: "readWrite", db: "mqtt"}]});
  6. ## Modify the configuration and disable anonymous authentication
  7. $ vi /usr/local/etc/mongod.conf
  8. security:
  9. authorization: enabled
  10. $ brew services restart mongodb

Create the mqtt_msg table:

  1. $ mongo 127.0.0.1/mqtt -uroot -ppublic
  2. db.createCollection("mqtt_msg");

Create rules:

Open EMQX DashboardSave offline Message to MongoDB - 图1 (opens new window) and select the “Rules” tab on the left.

Then fill in the rule SQL:

FROM description

t/#: The publisher publishes a message to trigger the action of saving of offline messages to MongoDB

$events/session_subscribed: The subscriber subscribes to topics to trigger the action of getting offline messages

$events/message_acked: The subscriber replies to the message ACK to trigger the action of deleting the offline message that has been received

  1. SELECT * FROM "t/#", "$events/session_subscribed", "$events/message_acked" WHERE topic =~ 't/#'

image-20211214151125535

Related actions:

Select “Add Action” on the “Action” interface, and then select “Offline messages” and “Offline Msg to MongoDB” in the “Action Type” drop-down box

image-20211214151154689

Now that the resource drop-down box is empty, and you can click “Create” in the upper right corner to create a MongoDB resource:

image-20211214151834553

The “Create” dialog box pops up:

image-20211214151326446

Fill in the resource configuration:

Fill in the real MongoDB server address and the values corresponding to other configurations, and then click the “Test Connection” button to ensure that the connection test is successful.

Finally click the “Confirm” button.

image-20211214151354243

Return to the action interface and click “Confirm”.

image-20211214151425343

Return to the rule creation interface and click “Create”.

image-20211214151455755

The rule has been created, and you can send a piece of data through the WebSocket client of Dashboard (The QoS of the published message must be greater than 0):

image-20211214151531162

After the message is sent, you can see the message is saved in MongoDB through mongo:

  1. db.mqtt_msg.find()

Save offline Message to MongoDB - 图10

Use another client to subscribe to the topic “t/1” (the QoS of the subscribed topic must be greater than 0, otherwise the message will be received repeatedly):

Save offline Message to MongoDB - 图11

After subscribing, you will receive the offline message saved in MongoDB immediately:

Save offline Message to MongoDB - 图12

Offline messages will be deleted in MongoDB after being received:

Save offline Message to MongoDB - 图13