RabbitMQ 配置 MQTT 服务

RabbitMQ 可以说是一个功能非常强大的消息队列了,它支持很多的协议,比如 MQTT,STOMP,其中 MQTT 是物联网中非常重要的协议。

RabbitMQ 自带了 MQTT 插件,默认没有开启,只要执行命令:rabbitmq-plugins enable rabbitmq_mqtt 开启即可。Eclipse Paho 项目提供了很多的 MQTT 客户端,这里使用 Python 客户端。

RabbitMQ 默认是使用 guest 账号,由于安全性的原因,通常会删除这个账号,但是 MQTT 默认会使用 guest 账号,因此需要配置 MQTT 默认连接账号,不然将无法连接。

使用 web 页面在后台新建一个账号,给账号分配跟(/)权限,在配置文件:/etc/rabbitmq/rabbitmq.conf 添加:

mqtt.listeners.tcp.default = 1883
## Default MQTT with TLS port is 8883
# mqtt.listeners.ssl.default = 8883

# anonymous connections, if allowed, will use the default
# credentials specified here
mqtt.allow_anonymous  = true
mqtt.default_user     = new-user
mqtt.default_pass     = new-user-passwd

mqtt.vhost            = /
mqtt.exchange         = amq.topic
# 24 hours by default
mqtt.subscription_ttl = 86400000
mqtt.prefetch         = 10

可以添加一些额外选项:

mqtt.listeners.tcp.1 = 127.0.0.1:1883
mqtt.listeners.tcp.2 = ::1:1883

mqtt.tcp_listen_options.backlog = 4096
mqtt.tcp_listen_options.recbuf  = 131072
mqtt.tcp_listen_options.sndbuf  = 131072

mqtt.tcp_listen_options.keepalive = true
mqtt.tcp_listen_options.nodelay   = true

mqtt.tcp_listen_options.exit_on_close = true
mqtt.tcp_listen_options.send_timeout  = 120

最后重启 RabbitMQ 即可:sudo service rabbitmq-server restart

我们试着使用 Python 来测试一下 MQTT 服务,安装客户端:pip install paho-mqtt

subscribe.py 文件:

import paho.mqtt.client as mqtt

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("iot")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("xxx.com", 1883, 60)

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()

publish.py 文件:

import paho.mqtt.client as mqtt
from time import sleep

client = mqtt.Client()
client.connect("xxx.com", 1883, 60)

while (True):

    client.publish("iot", payload="hello world.")
    sleep(1)

分别执行这两个文件即可,应该可以看到已经有数据打印出来了。