MQTT(MQ Telemetry Transport),消息隊列遙測傳輸協議,輕量級的發佈/訂閱協議, 適用於一些條件比較苛刻的環境,進行低帶寬、不可靠或間歇性的通訊。目前已是物聯網消息通訊事實上的標準協議了。值得一提的是mqtt提供三種不一樣質量的消息服務:
software · mqtt/mqtt.github.io Wiki
服務器操做系統爲CentOS7.0,使用最簡單的yum安裝
1.先加入yum源:
在/etc/yum.repos.d/目錄中新建一個mosquitto.repo文件,裏面寫入:
[home_oojah_mqtt] type=rpm-md baseurl=http://download.opensuse.org/repositories/home:/oojah:/mqtt/CentOS_CentOS-7/ gpgcheck=1 gpgkey=http://download.opensuse.org/repositories/home:/oojah:/mqtt/CentOS_CentOS-7//repodata/repomd.xml.key enabled=1
- name=mqtt (CentOS_CentOS-7)
熟悉命令的能夠直接下載到服務器中重命名http://download.opensuse.org/repositories/home:/oojah:/mqtt/CentOS_CentOS-7/home:oojah:mqtt.repo
不熟悉命令操做的(好比說我)就直接新建文件ftp上傳吧。
2.開始安裝
yum search all mosquittoyum install mosquitto mosquitto-clients
第一步先查找一下全部關於mosquitto的模塊。
顯現的模塊後面功能簡介,這裏我先安裝了mosquitto mosquitto-clients兩個模塊用於後面的測試,之後要用上什麼模塊我再安裝。
3.配置
安裝完成以後,全部配置文件會被放置於/etc/mosquitto/目錄下,
其中最重要的就是Mosquitto的配置文件,即mosquitto.conf
# Place your local configuration in /etc/mosquitto/conf.d/ 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
自定義的配置文件是放在/etc/mosquitto/conf.d/文件夾中,文件以.conf爲擴展名。詳細的配置參數參考mosquitto.conf.example
# ================================================================= # General configuration # ================================================================= # 客戶端心跳的間隔時間 #retry_interval 20 # 系統狀態的刷新時間 #sys_interval 10 # 系統資源的回收時間,0表示儘快處理 #store_clean_interval 10 # 服務進程的PID #pid_file /var/run/mosquitto.pid # 服務進程的系統用戶 #user mosquitto # 客戶端心跳消息的最大併發數 #max_inflight_messages 10 # 客戶端心跳消息緩存隊列 #max_queued_messages 100 # 用於設置客戶端長鏈接的過時時間,默認永不過時 #persistent_client_expiration# =================================================================# Default listener# =================================================================# 服務綁定的IP地址#bind_address# 服務綁定的端口號#port 1883# 容許的最大鏈接數,-1表示沒有限制#max_connections -1# cafile:CA證書文件# capath:CA證書目錄# certfile:PEM證書文件# keyfile:PEM密鑰文件#cafile#capath#certfile#keyfile# 必須提供證書以保證數據安全性#require_certificate false# 若require_certificate值爲true,use_identity_as_username也必須爲true#use_identity_as_username false# 啓用PSK(Pre-shared-key)支持#psk_hint# SSL/TSL加密算法,能夠使用「openssl ciphers」命令獲取# as the output of that command.#ciphers# =================================================================# Persistence# =================================================================# 消息自動保存的間隔時間#autosave_interval 1800# 消息自動保存功能的開關#autosave_on_changes false# 持久化功能的開關persistence true# 持久化DB文件#persistence_file mosquitto.db# 持久化DB文件目錄#persistence_location /var/lib/mosquitto/# =================================================================# Logging# =================================================================# 4種日誌模式:stdout、stderr、syslog、topic# none 則表示不記日誌,此配置能夠提高些許性能log_dest none# 選擇日誌的級別(可設置多項)#log_type error#log_type warning#log_type notice#log_type information# 是否記錄客戶端鏈接信息#connection_messages true# 是否記錄日誌時間#log_timestamp true# =================================================================# Security# =================================================================# 客戶端ID的前綴限制,可用於保證安全性#clientid_prefixes# 容許匿名用戶#allow_anonymous true# 用戶/密碼文件,默認格式:username:password#password_file# PSK格式密碼文件,默認格式:identity:key#psk_file# pattern write sensor/%u/data# ACL權限配置,經常使用語法以下:# 用戶限制:user <username># 話題限制:topic [read|write] <topic># 正則限制:pattern write sensor/%u/data#acl_file# =================================================================# Bridges# =================================================================# 容許服務之間使用「橋接」模式(可用於分佈式部署)#connection <name>#address <host>[:<port>]#topic <topic> [[[out | in | both] qos-level] local-prefix remote-prefix]# 設置橋接的客戶端ID#clientid # 橋接斷開時,是否清除遠程服務器中的消息 #cleansession false # 是否發佈橋接的狀態信息 #notifications true # 設置橋接模式下,消息將會發布到的話題地址 # $SYS/broker/connection/<clientid>/state #notification_topic # 設置橋接的keepalive數值 #keepalive_interval 60 # 橋接模式,目前有三種:automatic、lazy、once #start_type automatic # 橋接模式automatic的超時時間 #restart_timeout 30 # 橋接模式lazy的超時時間 #idle_timeout 60 # 橋接客戶端的用戶名 #username # 橋接客戶端的密碼 #password # bridge_cafile:橋接客戶端的CA證書文件 # bridge_capath:橋接客戶端的CA證書目錄 # bridge_certfile:橋接客戶端的PEM證書文件 # bridge_keyfile:橋接客戶端的PEM密鑰文件 #bridge_cafile #bridge_capath #bridge_certfile #bridge_keyfile # 本身的配置能夠放到如下目錄中 include_dir /etc/mosquitto/conf.d
mosquitto -c /etc/mosquitto/mosquitto.conf -d sudo /etc/init.d/mosquitto start
前面已經開啓了服務,若是沒有請參考前面步驟。在本例中,發佈者、代理和訂閱者均爲localhsot,可是在實際的狀況下三種並非同一個設備,在mosquitto中可經過-h(--host)設置主機名稱(hostname)。爲了實現這個簡單的測試案例,須要在linux中打開三個控制檯,分別表明代理服務器、發佈者和訂閱者。
1、開啓另外一個終端窗口,運行訂閱程序mosquitto_sub:
注意:
消息推送的發佈和訂閱要有主題,選項[-t] 主題,即:mosquitto -t 主題
如需指定用戶名稱則加選項[-i] 用戶名,即:mosquitto_sub -t 主題 -i 訂閱端
mosquitto_sub -t mqtt
2、開啓另外一個終端窗口,運行發佈程序mosquitto_pub:
指定消息推送的主題,發佈端用戶名和消息:
mosquitto_pub -t 主題 -i 發佈端 -h 主機 -m 你好
*注意:若是消息中間有空格則消息要用引號括起來。
mosquitto_pub -h localhost -t mqtt -m "hello world."
這時候前面那個訂閱窗口就能夠收到」hello world」的消息了。
Python的安裝環境就不講了。最新的paho-mqtt1.1使用下面的命令安裝
pip install paho-mqtt
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("mqtt")#訂閱,第一個參數是訂閱的主題# 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_connectclient.on_message = on_messageclient.connect("XXXXXXXXXX", 1883, 60)#第一個參數爲主機名,及Mosquitto所在服務器,第二個參數是端口# 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()
接下來我在服務器控制檯發佈一個消息
回頭看訂閱方
已經收到了推送的消息。
參考:mqtt消息中間件mosquitto的安裝和配置 - 斜風細雨