Golang中使用Mqtt的方法示例
MQTT 是一種基于發(fā)布/訂閱模式的 輕量級(jí)物聯(lián)網(wǎng)消息傳輸協(xié)議 ,可以用極少的代碼和帶寬為聯(lián)網(wǎng)設(shè)備提供實(shí)時(shí)可靠的消息服務(wù),它廣泛應(yīng)用于物聯(lián)網(wǎng)、移動(dòng)互聯(lián)網(wǎng)、智能硬件、車聯(lián)網(wǎng)、電力能源等行業(yè)。
本文主要介紹如何在 Golang 項(xiàng)目中使用 github.com/eclipse/paho.mqtt.golang 客戶端庫(kù) ,實(shí)現(xiàn)客戶端與 MQTT 服務(wù)器 的連接、訂閱、收發(fā)消息等功能。
項(xiàng)目初始化
環(huán)境為1.23.2
本項(xiàng)目使用 paho.mqtt.golang 作為 MQTT 客戶端庫(kù),安裝:
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) // 訂閱主題時(shí)的消息處理函數(shù) client := mqtt.NewClient(opts) if token := client.Connect(); token.Wait() && token.Error() != nil { log.Fatal(token.Error()) os.Exit(1) } // 訂閱主題 // production/# 匹配 production/ 開(kāi)頭的主題 if token := client.Subscribe("production/#", 0, nil); token.Wait() && token.Error() != nil { log.Fatal(token.Error()) os.Exit(1) }
訂閱主題消息處理函數(shù)
func onMessageReceived(client mqtt.Client, message mqtt.Message) { now := time.Now() fmt.Printf("時(shí)間:%s\t接收topic: %s\tMessage: %s\n", now.Format("2006-01-02 15:04:05.000"), message.Topic(), message.Payload()) // 在這里將消息轉(zhuǎn)發(fā)回業(yè)務(wù)平臺(tái),您可以根據(jù)需要修改此部分 }
發(fā)送主題
// 玩具入庫(kù)數(shù)據(jù) toysProduce := map[string]interface{}{ "method": "produce", "params": map[string]interface{}{ "sex": "1", "name": "test", "ver": "V1.0.0", }, } mjson, _ := json.Marshal(toysProduce) //轉(zhuǎn)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("時(shí)間:%s\t接收topic: %s\tMessage: %s\n", now.Format("2006-01-02 15:04:05.000"), message.Topic(), message.Payload()) // 在這里將消息轉(zhuǎn)發(fā)回業(yè)務(wù)平臺(tái),您可以根據(jù)需要修改此部分 } 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) // 訂閱主題時(shí)的消息處理函數(shù) client := mqtt.NewClient(opts) if token := client.Connect(); token.Wait() && token.Error() != nil { log.Fatal(token.Error()) os.Exit(1) } // 訂閱主題 // production/# 匹配 production/ 開(kāi)頭的主題 if token := client.Subscribe("production/#", 0, nil); token.Wait() && token.Error() != nil { log.Fatal(token.Error()) os.Exit(1) } // 玩具入庫(kù)數(shù)據(jù) toysProduce := map[string]interface{}{ "method": "produce", "params": map[string]interface{}{ "sex": "1", "name": "test", "ver": "V1.0.0", }, } mjson, _ := json.Marshal(toysProduce) //轉(zhuǎn)json fmt.Println("發(fā)送數(shù)據(jù):", string(mjson)) // 發(fā)送代碼指令 token := client.Publish("production/create", 0, false, string(mjson)) token.Wait() // 處理系統(tǒng)信號(hào),以便在接收到SIGINT或SIGTERM時(shí)優(yōu)雅地關(guān)閉程序 signalChan := make(chan os.Signal, 1) signal.Notify(signalChan, os.Interrupt, syscall.SIGTERM) <-signalChan fmt.Println("Received signal, shutting down...") client.Disconnect(250) }
到此這篇關(guān)于Golang中使用Mqtt的方法示例的文章就介紹到這了,更多相關(guān)Golang使用Mqtt內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go語(yǔ)言Http?Server框架實(shí)現(xiàn)一個(gè)簡(jiǎn)單的httpServer
這篇文章主要為大家介紹了Go語(yǔ)言Http?Server框架實(shí)現(xiàn)一個(gè)簡(jiǎn)單的httpServer抽象,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04Go語(yǔ)言基礎(chǔ)模板設(shè)計(jì)模式示例詳解
這篇文章主要為大家介紹了Go語(yǔ)言基礎(chǔ)設(shè)計(jì)模式之模板模式的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11Golang環(huán)境變量設(shè)置和查看工具go env詳解
go env 是 Go 工具鏈中的一個(gè)命令,用于設(shè)置和查看當(dāng)前 Golang 環(huán)境的相關(guān)信息,對(duì)于理解、編譯和運(yùn)行 Golang 程序非常有用,本文就給大家簡(jiǎn)單的介紹一下Golang環(huán)境變量設(shè)置和查看工具go env,需要的朋友可以參考下2023-07-07Go語(yǔ)言實(shí)現(xiàn)websocket推送程序
這篇文章主要介紹了Go語(yǔ)言實(shí)現(xiàn)websocket推送程序,WebSocket是基于TCP的一個(gè)雙向傳輸數(shù)據(jù)的協(xié)議,和HTTP協(xié)議一樣,是在應(yīng)用層的,他的出現(xiàn),是為了解決網(wǎng)頁(yè)進(jìn)行持久雙向傳輸數(shù)據(jù)的問(wèn)題2023-01-01一文帶你了解Go語(yǔ)言中的I/O接口設(shè)計(jì)
I/O?操作在編程中扮演著至關(guān)重要的角色,它涉及程序與外部世界之間的數(shù)據(jù)交換,下面我們就來(lái)簡(jiǎn)單了解一下Go語(yǔ)言中的?I/O?接口設(shè)計(jì)吧2023-06-06深入解析golang中的標(biāo)準(zhǔn)庫(kù)flag
Go語(yǔ)言內(nèi)置的flag包實(shí)現(xiàn)了命令行參數(shù)的解析,flag包使得開(kāi)發(fā)命令行工具更為簡(jiǎn)單,下面通過(guò)本文給大家詳細(xì)介紹下golang中的標(biāo)準(zhǔn)庫(kù)flag相關(guān)知識(shí),感興趣的朋友一起看看吧2021-11-11