Eclipse Mosquitto是一個開源消息代理,實現(xiàn)了MQTT協(xié)議版本3.1和3.1.1官研。Mosquitto輕量丛肢,適用于低功耗單板計算機(jī)到完整服務(wù)器的所有設(shè)備。Mosquitto項目還提供了用于實現(xiàn)MQTT客戶端的C庫以及非常受歡迎的mosquitto_pub和mosquitto_sub命令行MQTT客戶端罩扇。
其他服務(wù)器代理實現(xiàn):https://github.com/mqtt/mqtt.github.io/wiki/servers
各操作系統(tǒng)安裝指引:https://mosquitto.org/download/
1. 下載安裝
以Ubuntu16為例
- 添加到存儲庫列表
sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
- 更新軟件包
sudo apt-get update
- 安裝
sudo apt-get install mosquitto
- 安裝命令行客戶端
sudo apt-get install mosquitto-clients
2. 配置
2.1 主配置文件mosquitto.conf
pid_file /var/run/mosquitto.pid
# 消息持久存儲
persistence true
persistence_location /var/lib/mosquitto/
# 日志文件
log_dest file /var/log/mosquitto/mosquitto.log
# 其他配置
include_dir /etc/mosquitto/conf.d
# 禁止匿名訪問
allow_anonymous false
# 認(rèn)證配置
password_file /etc/mosquitto/pwfile
# 權(quán)限配置
acl_file /etc/mosquitto/aclfile
2.2 認(rèn)證配置pwfile
- 沒有則創(chuàng)建文件
touch /etc/mosquitto/pwfile
- 服務(wù)開啟后,輸入如下命令,根據(jù)提示輸入兩遍密碼
mosquitto_passwd /etc/mosquitto/pwfile 用戶名
2.3 權(quán)限配置aclfile
- 打開文件
vim /etc/mosquitto/aclfile
- 編輯內(nèi)容
# 李雷只能發(fā)布以test為前綴的主題,訂閱以$SYS開頭的主題即系統(tǒng)主題
user lilei
topic write test/#
topic read $SYS/#
# 韓梅梅只能訂閱以test為前綴的主題
user hanmeimei
topic read test/#
3. 啟動
-c:指定特定配置文件啟動
-d:后臺運行
mosquitto -c /etc/mosquitto/mosquitto.conf -d
4. 測試
發(fā)布使用mosquitto_pub命令婆芦,訂閱使用mosquitto_sub命令。常用參數(shù)介紹:
參數(shù) | 描述 |
---|---|
-h | 服務(wù)器主機(jī)喂饥,默認(rèn)localhost |
-t | 指定主題 |
-u | 用戶名 |
-P | 密碼 |
-i | 客戶端id消约,唯一 |
-m | 發(fā)布的消息內(nèi)容 |
訂閱
mosquitto_sub -h localhost -t "test/#" -u hanmeimei -P 123456 -i "client1"
訂閱系統(tǒng)主題
# 訂閱客戶端存活連接數(shù)
mosquitto_sub -h localhost –t '$SYS/broker/clients/active' -u lilei -P 123456 -i "client2"
發(fā)布
mosquitto_pub -h localhost -t "test/abc" -u lilei -P 123456 -i "client3" -m "How are you?"
鏈接
- 項目網(wǎng)站:https://www.eclipse.org/paho
- Eclipse項目信息:https://projects.eclipse.org/projects/iot.paho
- GitHub:https://github.com/eclipse/paho.mqtt.java
- MQTT Java客戶端的使用:http://www.reibang.com/p/65e1748a930c
- Spring支持:http://www.reibang.com/p/6b60858b7d44