Golang MQTT 的使用 實現發佈訂閱
Eclipse Paho MQTT Go Client 爲 Eclipse Paho 項目下的 Go 語言版客戶端庫,該庫能夠連接到 MQTT Broker 以發佈消息,訂閱主題並接收已發佈的消息,支持完全異步的操作模式。
官方源代碼地址: github.com/eclipse/paho.mqtt.golang
Go 應用使用 mqtt 通信協議的時候, 是作爲 client 端使用的, server 端自然需要一個服務來承載, 有很多軟件提供 MQTT 協議支持, 比如 mosquitto mqtt, emqx, smqtt, rabbitmq mqtt, pulsar mop mqtt 等等.
MQTT 服務安裝
Centos 離線安裝 RabbitMQ 並開啓 MQTT
Linux 安裝 mosquitto mqtt 幾種方式
emqx broker 安裝
docker 安裝 SMQTT
Golang 使用 MQTT
#下載MQTT依賴包
go get github.com/eclipse/paho.mqtt.golang
Go 語言的 Paho MQTT 連接 EMQX Broker 例子,並進行消息收發
package main
import (
"fmt"
uuid "github.com/satori/go.uuid"
"os"
"strings"
"time"
"github.com/eclipse/paho.mqtt.golang"
)
var fallbackFun mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
//打印收到的topic和內容
fmt.Printf("topic: %s\n", msg.Topic())
fmt.Printf("msg: %s\n", msg.Payload())
//收到的topic $test/msg/liang/get
//處理發佈的topic $abcd/msg/liang/set
split := strings.Split(msg.Topic(), "/")
liang := split[2]
setTopic := "$abcd/msg/" + liang + "/set"
//處理要發送的數據
data := "{\"msg\":\"hello\"}"
// 處理完之後 發佈消息 $abcd/msg/liang/set
client.Publish(setTopic, 0, false, data)
}
func main() {
clientId := uuid.NewV4()
opts := mqtt.NewClientOptions().AddBroker("tcp://192.168.1.8:1883").SetClientID(fmt.Sprintf("%s", clientId))
opts.SetKeepAlive(60 * time.Second)
// 設置消息回調處理函數 fallbackFun
opts.SetDefaultPublishHandler(fallbackFun)
opts.SetPingTimeout(1 * time.Second)
c := mqtt.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
// 訂閱主題 $test/msg/#
if token := c.Subscribe("$test/msg/#", 0, nil); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
select {
}
// 斷開連接
c.Disconnect(250)
time.Sleep(1 * time.Second)
}
參考鏈接: https://www.emqx.io/docs/zh/v4.4/development/go.html#mqtt-go-%E4%BD%BF%E7%94%A8%E7%A4%BA%E4%BE%8B
https://blog.justwe.site/post/tcp-mqtt/
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/j6_LWZOEBFOI4kbU0awOZg