Centos7-mqtt消息中間件mosquitto的安裝和配置


在以前發布的博客菜鳥是如何打造智能家居系統文章最后我提到了使用MQTT協議作為雲平台和設備之間的通信協議以達到消息傳遞的實時性,手機的消息推送也大多基於這種平台,首先搬來一段簡介。

    MQTTMQ Telemetry Transport),消息隊列遙測傳輸協議,輕量級的發布/訂閱協議, 適用於一些條件比較苛刻的環境,進行低帶寬、不可靠或間歇性的通信。目前已經是物聯網消息通信事實上的標准協議了。值得一提的是mqtt提供三種不同質量的消息服務:

  • 至多一次:消息發布完全依賴底層 TCP/IP 網絡。會發生消息丟失或重復。這一級別可用於如下情況,環境傳感器數據,丟失一次讀記錄無所謂,因為不久后還會有第二次發送。
  • 至少一次:確保消息到達,但消息重復可能會發生。
  • 只有一次:確保消息到達一次。這一級別可用於如下情況,在計費系統中,消息重復或丟失會導致不正確的結果。

一直沒時間搭建這個平台,前段時間到MQTT發現了一些很好的資源。

資源里既有基於MQTT(但不僅限於)開源消息代理中間件(Brokers/servers),又有測試客戶端,看了幾個代理中間件,也百度了一下,應用比較多的有ActiveMQApolloMosquitto等。先選擇一個沒那么復雜的Mosquitto來嘗嘗鮮。

Mosquitto一款實現了消息協議 MQTT v3.1 的開源消息代理軟件,提供輕量級的,支持可發布/可訂閱的的消息推送模式,使設備對設備之間的短消息通信變得簡單,比如現在應用廣泛的低功耗傳感器,手機、嵌入式計算、微型控制器等移動設備。

安裝:(參考官網 http://mosquitto.org/download/)

服務器操作系統為CentOS7.0,使用最簡單的yum安裝

1.先加入yum源:

/etc/yum.repos.d/目錄中新建一個mosquitto.repo文件,里面寫入:

  
  
  
          
  1. [home_oojah_mqtt]
  2. name=mqtt (CentOS_CentOS-7)
  3. type=rpm-md
  4. baseurl=http://download.opensuse.org/repositories/home:/oojah:/mqtt/CentOS_CentOS-7/
  5. gpgcheck=1
  6. gpgkey=http://download.opensuse.org/repositories/home:/oojah:/mqtt/CentOS_CentOS-7//repodata/repomd.xml.key
  7. enabled=1

熟悉命令的可以直接下載到服務器中重命名http://download.opensuse.org/repositories/home:/oojah:/mqtt/CentOS_CentOS-7/home:oojah:mqtt.repo

不熟悉命令操作的(比如說我)就直接新建文件ftp上傳吧。

2.開始安裝

   
   
   
           
  1. yum search all mosquitto
  2. yum install mosquitto mosquitto-clients

第一步先查找一下所有關於mosquitto的模塊。

顯現的模塊后面功能簡介,這里我先安裝了mosquitto mosquitto-clients兩個模塊用於后面的測試,以后要用上什么模塊我再安裝。

3.配置

安裝完成之后,所有配置文件會被放置於/etc/mosquitto/目錄下,



 其中最重要的就是Mosquitto的配置文件,即mosquitto.conf

   
   
   
           
  1. # Place your local configuration in /etc/mosquitto/conf.d/
  2. pid_file /var/run/mosquitto.pid
  3. persistence true
  4. persistence_location /var/lib/mosquitto/
  5. #log_dest file /var/log/mosquitto/mosquitto.log
  6. include_dir /etc/mosquitto/conf.d

自定義的配置文件是放在/etc/mosquitto/conf.d/文件夾中,文件以.conf為擴展名。詳細的配置參數參考mosquitto.conf.example

    
    
    
            
  1. # =================================================================
  2. # General configuration
  3. # =================================================================
  4. # 客戶端心跳的間隔時間
  5. #retry_interval 20
  6. # 系統狀態的刷新時間
  7. #sys_interval 10
  8. # 系統資源的回收時間,0表示盡快處理
  9. #store_clean_interval 10
  10. # 服務進程的PID
  11. #pid_file /var/run/mosquitto.pid
  12. # 服務進程的系統用戶
  13. #user mosquitto
  14. # 客戶端心跳消息的最大並發數
  15. #max_inflight_messages 10
  16. # 客戶端心跳消息緩存隊列
  17. #max_queued_messages 100
  18. # 用於設置客戶端長連接的過期時間,默認永不過期
  19. #persistent_client_expiration
  20. # =================================================================
  21. # Default listener
  22. # =================================================================
  23. # 服務綁定的IP地址
  24. #bind_address
  25. # 服務綁定的端口號
  26. #port 1883
  27. # 允許的最大連接數,-1表示沒有限制
  28. #max_connections -1
  29. # cafile:CA證書文件
  30. # capath:CA證書目錄
  31. # certfile:PEM證書文件
  32. # keyfile:PEM密鑰文件
  33. #cafile
  34. #capath
  35. #certfile
  36. #keyfile
  37. # 必須提供證書以保證數據安全性
  38. #require_certificate false
  39. # 若require_certificate值為true,use_identity_as_username也必須為true
  40. #use_identity_as_username false
  41. # 啟用PSK(Pre-shared-key)支持
  42. #psk_hint
  43. # SSL/TSL加密算法,可以使用“openssl ciphers”命令獲取
  44. # as the output of that command.
  45. #ciphers
  46. # =================================================================
  47. # Persistence
  48. # =================================================================
  49. # 消息自動保存的間隔時間
  50. #autosave_interval 1800
  51. # 消息自動保存功能的開關
  52. #autosave_on_changes false
  53. # 持久化功能的開關
  54. persistence true
  55. # 持久化DB文件
  56. #persistence_file mosquitto.db
  57. # 持久化DB文件目錄
  58. #persistence_location /var/lib/mosquitto/
  59. # =================================================================
  60. # Logging
  61. # =================================================================
  62. # 4種日志模式:stdout、stderr、syslog、topic
  63. # none 則表示不記日志,此配置可以提升些許性能
  64. log_dest none
  65. # 選擇日志的級別(可設置多項)
  66. #log_type error
  67. #log_type warning
  68. #log_type notice
  69. #log_type information
  70. # 是否記錄客戶端連接信息
  71. #connection_messages true
  72. # 是否記錄日志時間
  73. #log_timestamp true
  74. # =================================================================
  75. # Security
  76. # =================================================================
  77. # 客戶端ID的前綴限制,可用於保證安全性
  78. #clientid_prefixes
  79. # 允許匿名用戶
  80. #allow_anonymous true
  81. # 用戶/密碼文件,默認格式:username:password
  82. #password_file
  83. # PSK格式密碼文件,默認格式:identity:key
  84. #psk_file
  85. # pattern write sensor/%u/data
  86. # ACL權限配置,常用語法如下:
  87. # 用戶限制:user <username>
  88. # 話題限制:topic [read|write] <topic>
  89. # 正則限制:pattern write sensor/%u/data
  90. #acl_file
  91. # =================================================================
  92. # Bridges
  93. # =================================================================
  94. # 允許服務之間使用“橋接”模式(可用於分布式部署)
  95. #connection <name>
  96. #address <host>[:<port>]
  97. #topic <topic> [[[out | in | both] qos-level] local-prefix remote-prefix]
  98. # 設置橋接的客戶端ID
  99. #clientid
  100. # 橋接斷開時,是否清除遠程服務器中的消息
  101. #cleansession false
  102. # 是否發布橋接的狀態信息
  103. #notifications true
  104. # 設置橋接模式下,消息將會發布到的話題地址
  105. # $SYS/broker/connection/<clientid>/state
  106. #notification_topic
  107. # 設置橋接的keepalive數值
  108. #keepalive_interval 60
  109. # 橋接模式,目前有三種:automatic、lazy、once
  110. #start_type automatic
  111. # 橋接模式automatic的超時時間
  112. #restart_timeout 30
  113. # 橋接模式lazy的超時時間
  114. #idle_timeout 60
  115. # 橋接客戶端的用戶名
  116. #username
  117. # 橋接客戶端的密碼
  118. #password
  119. # bridge_cafile:橋接客戶端的CA證書文件
  120. # bridge_capath:橋接客戶端的CA證書目錄
  121. # bridge_certfile:橋接客戶端的PEM證書文件
  122. # bridge_keyfile:橋接客戶端的PEM密鑰文件
  123. #bridge_cafile
  124. #bridge_capath
  125. #bridge_certfile
  126. #bridge_keyfile
  127. # 自己的配置可以放到以下目錄中
  128. include_dir /etc/mosquitto/conf.d


4. 啟動服務,兩種方式
   
   
   
           
  1. mosquitto -c /etc/mosquitto/mosquitto.conf -d
  2. sudo /etc/init.d/mosquitto start


演示部分:

前面已經開啟了服務,如果沒有請參考前面步驟。在本例中,發布者、代理和訂閱者均為localhsot,但是在實際的情況下三種並不是同一個設備,在mosquitto中可通過-h(--host)設置主機名稱(hostname)。為了實現這個簡單的測試案例,需要在linux中打開三個控制台,分別代表代理服務器、發布者和訂閱者。


一、開啟另一個終端窗口,運行訂閱程序mosquitto_sub:

注意:

消息推送的發布和訂閱要有主題,選項[-t] 主題,即:mosquitto -t 主題

如需指定用戶名稱則加選項[-i] 用戶名,即:mosquitto_sub -t 主題 -i 訂閱端

   
   
   
           
  1. mosquitto_sub -t mqtt

二、開啟另一個終端窗口,運行發布程序mosquitto_pub:

指定消息推送的主題,發布端用戶名和消息:

mosquitto_pub -t 主題 -i 發布端 -h 主機 -m 你好

*注意:如果消息中間有空格則消息要用引號括起來。

   
   
   
           
  1. mosquitto_pub -h localhost -t mqtt -m "hello world."

這時候前面那個訂閱窗口就可以收到”hello world”的消息了。

另外Mosquitto官方也提供了C++和Python寫的測試代碼,這里測試一下Python客戶端 paho-mqtt 1.1

Python的安裝環境就不講了。最新的paho-mqtt1.1使用下面的命令安裝

   
   
   
           
  1. pip install paho-mqtt
接下來寫一個測試的Python文件,具體的接口文檔建議參考官方文檔。
    
    
    
            
  1. import paho.mqtt.client as mqtt
  2. # The callback for when the client receives a CONNACK response from the server.
  3. def on_connect(client, userdata, flags, rc):
  4. print("Connected with result code "+str(rc))
  5. # Subscribing in on_connect() means that if we lose the connection and
  6. # reconnect then subscriptions will be renewed.
  7. client.subscribe("mqtt")
  8. #訂閱,第一個參數是訂閱的主題
  9. # The callback for when a PUBLISH message is received from the server.
  10. def on_message(client, userdata, msg):
  11. print(msg.topic+" "+str(msg.payload))
  12. client = mqtt.Client()
  13. client.on_connect = on_connect
  14. client.on_message = on_message
  15. client.connect("XXXXXXXXXX", 1883, 60)
  16. #第一個參數為主機名,及Mosquitto所在服務器,第二個參數是端口
  17. # Blocking call that processes network traffic, dispatches callbacks and
  18. # handles reconnecting.
  19. # Other loop*() functions are available that give a threaded interface and a
  20. # manual interface.
  21. client.loop_forever()
執行這個Python文件

接下來我在服務器控制台發布一個消息

回頭看訂閱方

已經收到了推送的消息。

參考:mqtt消息中間件mosquitto的安裝和配置 - 斜風細雨

 






免責聲明!

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



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