Topic Rewrite

    Open , click the “Modules” tab on the left, and choose to add:

    image-20200927213049265

    Select MQTT topic rewrite module

    Configure related parameters

    After clicking add, the module is added

    image-20200927213049265

    The rewrite rules are divided into Pub rules and Sub rules. Pub rules match the topics carried in PUSHLISH packets, and Sub rules match the topics carried in SUBSCRIBE and UNSUBSCRIBE packets.

    Each rewrite rule consists of three parts: subject filter, regular expression, and target expression. Under the premise that the subject rewriting function is enabled, when EMQX receives a subject-based MQTT message such as a PUBLISH message, it will use the subject of the message to sequentially match the subject filter part of the rule in the configuration file. If the match is successful, the regular expression is used to extract the information in the subject, and then replaced with the target expression to form a new subject.

    Variables in the format of can be used in the target expression to match the elements extracted from the regular expression. The value of $N is the Nth element extracted from the regular expression. For example, $1 is the regular expression. The first element extracted by the expression.

    It should be noted that EMQX uses reverse order to read the rewrite rules in the configuration file. When a topic can match the topic filter of multiple topic rewrite rules at the same time, EMQX will only use the first rule it matches. Rewrite. If the regular expression in this rule does not match the subject of the MQTT message, the rewriting will fail, and no other rules will be attempted for rewriting. Therefore, users need to carefully design MQTT message topics and topic rewriting rules when using them.

    Add the topic rewriting rules in the above figure and subscribe to y/a/z/b, y/def, x/1/2, x/y/2, x/y/zFive topic:

    • When the client subscribes to the topic of y/def, does not match any topic filter, so no topic rewriting is performed, and the topic of y/def is directly subscribed.

    • When the client subscribes to the topic y/a/z/b, y/a/z/b matches the topic filter of y/+/z/#, and EMQX executes module.rewrite.sub. rule.1 rule, the element [a, b] is matched through regular regular expressions, and the second element that is matched is brought into y/z/$2, which actually subscribes to y/z/b topic.

    • When the client sends a message to the topic x/y/z, x/y/z matches both x/# and x/y/+ two topic filters, EMQX reads in reverse order The configuration is taken, so module.rewrite.pub.rule.2' is first matched. If the element is not matched by the regular expression, the subject rewriting is not performed, and the message is sent directly to thex/y/ztopic. It should be noted that even if the regular expression ofmodule.rewrite.pub.rule.2module.rewrite.pub.rule.1` again.