Get subscription relationship from MySQL

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

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

Initialize the MySQL database:

  1. $ mysql -u root -h localhost -ppublic
  2. create database mqtt;

Create the mqtt_sub table:

  1. DROP TABLE IF EXISTS `mqtt_sub`;
  2. CREATE TABLE `mqtt_sub` (
  3. `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  4. `clientid` varchar(64) DEFAULT NULL,
  5. `topic` varchar(180) DEFAULT NULL,
  6. `qos` tinyint(1) DEFAULT NULL,
  7. PRIMARY KEY (`id`),
  8. KEY `mqtt_sub_idx` (`clientid`,`topic`,`qos`),
  9. UNIQUE KEY `mqtt_sub_key` (`clientid`,`topic`),
  10. INDEX topic_index(`id`, `topic`)
  11. ) ENGINE=InnoDB DEFAULT CHARSET=utf8MB4;

TIP

The subscription relationship table structure cannot be modified. Please use the above SQL statement to create

Create rules:

Open EMQX DashboardGet subscription from MySQL - 图1 (opens new window) and select the “Rules” tab on the left.

Then fill in the rule SQL:

  1. SELECT * FROM "$events/client_connected"

Get subscription from MySQL - 图2

Related actions:

Select “Add Action” on the “Response Action” interface, and then select “Get Subscription List from MySQL” in the “Add Action” drop-down box

Get subscription from MySQL - 图3

Fill in the action parameters:

The action of “Get subscription list from MySQL” requires one parameter:

1). Associated resources. The resource drop-down box is empty now, and you can click “New” in the upper right corner to create a MySQL resource:

Get subscription from MySQL - 图4

The “Create Resource” dialog box pops up

Get subscription from MySQL - 图5

Fill in the resource configuration:

Fill in the real MySQL 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 “OK” button.

Get subscription from MySQL - 图6

Return to the response action interface and click “OK”.

Get subscription from MySQL - 图7

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

Get subscription from MySQL - 图8

The rule has been created, and you can insert a subscription relationship into MySQL through “mysql”:

  1. insert into mqtt_sub(clientid, topic, qos) values("test", "t1", 1);

Get subscription from MySQL - 图9

Log in to the device whose clientid is test via Dashboard:

Get subscription from MySQL - 图10

Check the “Subscription” list, and you can see that the Broker obtains the subscription relationship from MySQL and subscribes as the agent device:

Get subscription from MySQL - 图11