Golang中使用Mqtt的方法示例
MQTT 是一種基于發(fā)布/訂閱模式的 輕量級物聯(lián)網消息傳輸協(xié)議 ,可以用極少的代碼和帶寬為聯(lián)網設備提供實時可靠的消息服務,它廣泛應用于物聯(lián)網、移動互聯(lián)網、智能硬件、車聯(lián)網、電力能源等行業(yè)。
本文主要介紹如何在 Golang 項目中使用 github.com/eclipse/paho.mqtt.golang 客戶端庫 ,實現(xiàn)客戶端與 MQTT 服務器 的連接、訂閱、收發(fā)消息等功能。
項目初始化
環(huán)境為1.23.2
本項目使用 paho.mqtt.golang 作為 MQTT 客戶端庫,安裝:
go get github.com/eclipse/paho.mqtt.golang
連接Mqtt
opts := mqtt.NewClientOptions().AddBroker("tcp://broker.emqx.io:1883") opts.SetClientID("mqtt_golang_NTkxOD123213") // Client ID // opts.SetUsername("mqtt_toys") // 用戶名 // opts.SetPassword("to113gz") // 用戶密碼 opts.SetDefaultPublishHandler(onMessageReceived) // 訂閱主題時的消息處理函數 client := mqtt.NewClient(opts) if token := client.Connect(); token.Wait() && token.Error() != nil { log.Fatal(token.Error()) os.Exit(1) } // 訂閱主題 // production/# 匹配 production/ 開頭的主題 if token := client.Subscribe("production/#", 0, nil); token.Wait() && token.Error() != nil { log.Fatal(token.Error()) os.Exit(1) }
訂閱主題消息處理函數
func onMessageReceived(client mqtt.Client, message mqtt.Message) { now := time.Now() fmt.Printf("時間:%s\t接收topic: %s\tMessage: %s\n", now.Format("2006-01-02 15:04:05.000"), message.Topic(), message.Payload()) // 在這里將消息轉發(fā)回業(yè)務平臺,您可以根據需要修改此部分 }
發(fā)送主題
// 玩具入庫數據 toysProduce := map[string]interface{}{ "method": "produce", "params": map[string]interface{}{ "sex": "1", "name": "test", "ver": "V1.0.0", }, } mjson, _ := json.Marshal(toysProduce) //轉json // 發(fā)送代碼指令 token := client.Publish("production/create", 0, false, string(mjson)) token.Wait()
完成代碼
package main import ( "encoding/json" "fmt" "log" "os" "os/signal" "syscall" "time" mqtt "github.com/eclipse/paho.mqtt.golang" ) func onMessageReceived(client mqtt.Client, message mqtt.Message) { now := time.Now() fmt.Printf("時間:%s\t接收topic: %s\tMessage: %s\n", now.Format("2006-01-02 15:04:05.000"), message.Topic(), message.Payload()) // 在這里將消息轉發(fā)回業(yè)務平臺,您可以根據需要修改此部分 } func main() { opts := mqtt.NewClientOptions().AddBroker("tcp://broker.emqx.io:1883") opts.SetClientID("mqtt_golang_NTkxOD123213") // Client ID // opts.SetUsername("mqtt_toys") // 用戶名 // opts.SetPassword("to113gz") // 用戶密碼 opts.SetDefaultPublishHandler(onMessageReceived) // 訂閱主題時的消息處理函數 client := mqtt.NewClient(opts) if token := client.Connect(); token.Wait() && token.Error() != nil { log.Fatal(token.Error()) os.Exit(1) } // 訂閱主題 // production/# 匹配 production/ 開頭的主題 if token := client.Subscribe("production/#", 0, nil); token.Wait() && token.Error() != nil { log.Fatal(token.Error()) os.Exit(1) } // 玩具入庫數據 toysProduce := map[string]interface{}{ "method": "produce", "params": map[string]interface{}{ "sex": "1", "name": "test", "ver": "V1.0.0", }, } mjson, _ := json.Marshal(toysProduce) //轉json fmt.Println("發(fā)送數據:", string(mjson)) // 發(fā)送代碼指令 token := client.Publish("production/create", 0, false, string(mjson)) token.Wait() // 處理系統(tǒng)信號,以便在接收到SIGINT或SIGTERM時優(yōu)雅地關閉程序 signalChan := make(chan os.Signal, 1) signal.Notify(signalChan, os.Interrupt, syscall.SIGTERM) <-signalChan fmt.Println("Received signal, shutting down...") client.Disconnect(250) }
到此這篇關于Golang中使用Mqtt的方法示例的文章就介紹到這了,更多相關Golang使用Mqtt內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Go語言Http?Server框架實現(xiàn)一個簡單的httpServer
這篇文章主要為大家介紹了Go語言Http?Server框架實現(xiàn)一個簡單的httpServer抽象,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04Golang環(huán)境變量設置和查看工具go env詳解
go env 是 Go 工具鏈中的一個命令,用于設置和查看當前 Golang 環(huán)境的相關信息,對于理解、編譯和運行 Golang 程序非常有用,本文就給大家簡單的介紹一下Golang環(huán)境變量設置和查看工具go env,需要的朋友可以參考下2023-07-07