配置Mosquitto双向桥接避免无限循环问题咨询
解决Mosquitto双向桥接无限循环问题
你的问题核心是双向桥接时,两个Broker会互相转发对方桥接过来的消息,从而形成无限循环。以下是两种直接有效的解决方法:
方法一:使用not_local参数过滤桥接自身的消息
这是最简单的方案,不需要修改客户端或Nginx配置,仅调整Mosquitto的桥接规则即可。
修改第一个Mosquitto容器的桥接配置:
#bridges connection mosquitto2 address mosquitto2:1883 # 添加not_local参数,忽略来自本地桥接客户端的消息 topic test/# both 1 "" "" not_local remote_clientid bridge1 local_clientid bridge1_local try_private true
修改第二个Mosquitto容器的桥接配置:
#bridges connection mosquitto1 address mosquitto1:1883 topic test/# both 1 "" "" not_local remote_clientid bridge2 local_clientid bridge2_local try_private true
原理:
not_local参数会让桥接忽略来自local_clientid标识的本地客户端消息。- 当Broker A将客户端消息桥接到Broker B后,Broker B的桥接会识别到这条消息来自Broker A的桥接客户端(bridge1_local),不会再转发回Broker A,彻底切断循环。
方法二:仅转发来自Nginx的客户端消息
如果需要更精准地控制只转发通过1885端口(Nginx)过来的消息,可以通过给这类客户端标记特定ClientID前缀,再在桥接规则中过滤。
步骤1:让Nginx转发的客户端使用统一ClientID前缀
需要确保所有通过Nginx连接的客户端,其ClientID以特定前缀(比如nginx_)开头。如果客户端无法自行设置,可借助Nginx的MQTT模块(如ngx_mqtt)修改ClientID。
步骤2:修改桥接配置
第一个容器配置:
#bridges connection mosquitto2 address mosquitto2:1883 # out方向仅转发ClientID以nginx_开头的客户端消息 topic test/# out 1 "" "nginx_" # in方向接收所有消息 topic test/# in 1 remote_clientid bridge1 try_private true
第二个容器配置:
#bridges connection mosquitto1 address mosquitto1:1883 topic test/# out 1 "" "nginx_" topic test/# in 1 remote_clientid bridge2 try_private true
原理:
out 1 "" "nginx_"表示仅转发ClientID匹配nginx_前缀的客户端发布的消息。- 桥接自身的ClientID是
bridge1/bridge2,不符合前缀,所以不会被重复转发,避免循环。
推荐优先使用方法一,配置更简洁且不需要依赖额外客户端或Nginx模块修改。
内容的提问来源于stack exchange,提问作者adrian
相关产品推荐
相关产品推荐

