ubuntu下Mosquitto安裝及配置


ubuntu下Mosquitto安裝及配置

本文最近一次修改日期:2020-03-04 1:43 周三

Eclipse Mosquitto是一個開源消息代理,實現了MQTT協議版本3.1和3.1.1.Mosquitto輕量,適用於低功耗單板計算機到完整服務器的所有設備.

Mosquitto項目還提供了用於實現MQTT客戶端的C庫以及非常受歡迎的mosquitto_pub和mosquitto_sub命令行MQTT客戶端.

本文抄自:飛虎兄的文章Mosquitto 搭建及配置
本文參考:清明-心若淡定的文章訂閱mosquitto服務器狀態各主題

所超代碼,均已在ubuntu server 18.04 LTS上測試,
訂閱客戶端數量 $SYS/broker/clients/active (1.4版本已取消 //經測試我用的1.6.8的客戶端,這個命令並沒有取消
修改為$SYS/broker/clients/expired (當前連接的客戶端數量) //這個命令什么也沒返回,這是為什么?

其他服務器代理實現:https://github.com/mqtt/mqtt.github.io/wiki/servers
各操作系統安裝指引:https://mosquitto.org/download/

Mosquitto安裝

  • 添加存儲庫
sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
  • 更新軟件包
sudo apt-get update
  • 安裝
sudo apt-get install mosquitto -y
  • 安裝命令行客戶端
sudo apt-get install mosquitto-clients -y

配置

sudo nano /etc/mosquitto/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

# 認證配置
password_file /etc/mosquitto/pwfile

# 權限配置
acl_file /etc/mosquitto/aclfile
  • 認證配置pwfile

創建文件

sudo touch /etc/mosquitto/pwfile
  • 開啟服務開啟
sudo mosquitto_passwd /etc/mosquitto/pwfile bootloader #bootloader是我當前用戶名
  • 權限配置aclfile
sudo nano /etc/mosquitto/aclfile
# user1只能發布以test為前綴的主題,訂閱以$SYS開頭的主題即系統主題
user user1
topic write test/#
topic read $SYS/#

# user2只能訂閱以test為前綴的主題
user user2
topic read test/#

啟動服務端

#-c:指定特定配置文件啟動
#-d:后台運行
mosquitto -c /etc/mosquitto/mosquitto.conf -d

測試

發布使用mosquitto_pub命令,訂閱使用mosquitto_sub命令.常用參數介紹:

參數 描述
-h 服務器主機,默認localhost
-t 指定主題
-u 用戶名
-P 密碼
-i 客戶端id,唯一
-m 發布的消息內容
  • 訂閱
mosquitto_sub -h localhost -t "test/#" -u user2 -P 123456 -i "client1"
  • 訂閱系統主題
# 訂閱客戶端存活連接數
mosquitto_sub -h localhost -u user1 -P 123456 -i "client2" -t '$SYS/broker/clients/active'  #發布者 訂閱 者都算存活連接
  • 發布
mosquitto_pub -h localhost -t "test/abc" -u user1 -P 123456 -i "client3" -m "How are you?"

其他


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM