Save data to MySQL

Setup a MySQL database, and changes the username/password to root/public, taking Mac OSX for instance:

  1. $ brew install mysql
  2. $ brew services start mysql
  3. $ mysql -u root -h localhost -p
  4. ALTER USER 'root'@'localhost' IDENTIFIED BY 'public';

Initiate MySQL table:

  1. $ mysql -u root -h localhost -ppublic
  2. create "test" database:
  3. CREATE DATABASE test;
  4. create "t_mqtt_msg" table:
  5. USE test;
  1. CREATE TABLE `t_mqtt_msg` (
  2. `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  3. `msgid` varchar(64) DEFAULT NULL,
  4. `topic` varchar(255) NOT NULL,
  5. `qos` tinyint(1) NOT NULL DEFAULT '0',
  6. `payload` blob,
  7. `arrived` datetime NOT NULL,
  8. PRIMARY KEY (`id`),
  9. INDEX topic_index(`id`, `topic`)
  10. ) ENGINE=InnoDB DEFAULT CHARSET=utf8MB4;

image

Create a rule:

Go to EMQX DashboardSave data to MySQL - 图2 (opens new window), select the “rule” tab on the menu to the left.

Select “message.publish”, then type in the following SQL:

  1. SELECT * FROM "message.publish"

image

Bind an action:

Click on the “+ Add” button under “Action Handler”, and then select “Data to MySQL” in the pop-up dialog window.

image

Fill in the parameters required by the action:

Two parameters is required by action “Data to MySQL”:

1). SQL template. SQL template is the sql command you’d like to run when the action is triggered. In this example we’ll insert a message into mysql, so type in the following sql template:

  1. insert into t_mqtt_msg(msgid, topic, qos, payload, arrived) values (${id}, ${topic}, ${qos}, ${payload}, FROM_UNIXTIME(${timestamp}/1000))

Before data is inserted into the table, placeholders like ${key} will be replaced by the corresponding values.

image

2). Bind a resource to the action. Since the dropdown list “Resource” is empty for now, we create a new resource by clicking on the “New Resource” to the top right, and then select “MySQL”:

image

Configure the resource:

Set “MySQL Database” to “test”, “MySQL Username” to “root”, “MySQL Password” to “public”, and “Description” to “MySQL resource to 127.0.0.1:3306 db=test”, and click on the “Testing Connection” button to make sure the connection can be created successfully, and then click on the “Create” button.

image

Back to the “Actions” dialog, and then click on the “Confirm” button.

image

Back to the creating rule page, then click on “Create” button. The rule we created will be show in the rule list:

image

We have finished, testing the rule by sending an MQTT message to emqx:

  1. > Topic: "t/a"
  2. >
  3. > QoS: 1
  4. >
  5. > Payload: "hello"

Then inspect the MySQL table, verify a new record has been inserted:

image