Get subscription relationship from PostgreSQL

TIP

Support PostgreSQL 13 and below versions

Set up the PostgreSQL database, and take MacOS X as an example:

  1. $ brew install postgresql
  2. $ brew services start postgresql

Create the mqtt database:

  1. # Create a database named 'mqtt' with the username postgres
  2. $ createdb -U postgres mqtt
  3. $ psql -U postgres mqtt
  4. mqtt=> \dn;
  5. List of schemas
  6. Name | Owner
  7. --------+-------
  8. public | postgres
  9. (1 row)

Create the mqtt_sub table:

  1. $ psql -U postgres mqtt
  2. CREATE TABLE mqtt_sub(
  3. id SERIAL8 primary key,
  4. clientid character varying(64),
  5. topic character varying(255),
  6. qos integer,
  7. UNIQUE (clientid, topic)
  8. );

TIP

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

Create rules:

Open EMQX DashboardGet subscription from PostgreSQL - 图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 PostgreSQL - 图2

Related actions:

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

Get subscription from PostgreSQL - 图3

Fill in the action parameters:

The action of “Get subscription list from PostgreSQL” 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 PostgreSQL resource:

Get subscription from PostgreSQL - 图4

The “Create Resource” dialog box pops up

Get subscription from PostgreSQL - 图5

Fill in the resource configuration:

Fill in the real PostgreSQL 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 PostgreSQL - 图6

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

Get subscription from PostgreSQL - 图7

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

Get subscription from PostgreSQL - 图8

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

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

Get subscription from PostgreSQL - 图9

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

Get subscription from PostgreSQL - 图10

查看“订阅”列表,可以看到 Broker 从 PostgreSQL 里面获取到订阅关系,并代理设备订阅:

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

Get subscription from PostgreSQL - 图11