Topic Rewrite
Open , click the “Modules” tab on the left, and choose to add:
Select MQTT topic rewrite module
Configure related parameters
After clicking add, the module is added
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/z
Five 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 ofy/def
is directly subscribed.When the client subscribes to the topic
y/a/z/b
,y/a/z/b
matches the topic filter ofy/+/z/#
, and EMQX executesmodule.rewrite.sub. rule.1
rule, the element[a, b]
is matched through regular regular expressions, and the second element that is matched is brought intoy/z/$2
, which actually subscribes toy/z/b
topic.When the client sends a message to the topic
x/y/z
,x/y/z
matches bothx/#
andx/y/+
two topic filters, EMQX reads in reverse order The configuration is taken, somodule.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 the
x/y/ztopic. It should be noted that even if the regular expression of
module.rewrite.pub.rule.2module.rewrite.pub.rule.1` again.