Golang實(shí)現(xiàn)MQTT服務(wù)

1. 加載mqtt包

go get -u github.com/eclipse/paho.mqtt.golang
go mod vendor

2. 初始化MQTT服務(wù)

var client mqtt.Client

// 初始化MQTT服務(wù)
func NewClient() {
   if client == nil {
       opts := mqtt.NewClientOptions()
       opts.AddBroker("tcp://broker.emqx.io:1883") // 這個(gè)中轉(zhuǎn)服務(wù)器不需要任何賬號(hào)密碼
       opts.SetClientID("go_mqtt_client1")
       // opts.SetUsername("")
       // opts.SetPassword("")
       opts.OnConnect = func(c mqtt.Client) {
           fmt.Println("MQTT鏈接成功!")
       }
       opts.OnConnectionLost = func(c mqtt.Client, err error) {
           fmt.Println("MQTT斷開鏈接!", err.Error())
           fmt.Println("嘗試重新鏈接!")
           NewClient()
       }
       client = mqtt.NewClient(opts)
   }

   if token := client.Connect(); token.Wait() && token.Error() != nil {
       fmt.Println(token.Error())
   }

   // 訂閱事件
   for _, subscribe := range subscribes {
       subscribe()
   }
}

3. 發(fā)布消息與訂閱消息調(diào)用方法

// 發(fā)布消息 ClientSend("topic/publish/example", 2, false, `{"code":0, "msg":"hello world!"}`)
func ClientSend(topic string, qos byte, retained bool, payload interface{}) error {
    if token := client.Publish(topic, qos, retained, payload); token.Wait() && token.Error() != nil {
        fmt.Println("消息發(fā)布失敗!", token.Error())
        return token.Error()
    }
    return nil
}

// 訂閱消息
func ClientSubscribe(topic string, qos byte, callback mqtt.MessageHandler, err func(error)) {
    if token := client.Subscribe(topic, qos, func(c mqtt.Client, msg mqtt.Message) {
        callback(c, msg)
    }); token.Wait() && token.Error() != nil {
        err(token.Error())
    }
}

4. 發(fā)布消息

err := ClientSend("topic/publish/example", 2, false, `{"code":0, "msg":"hello world!"}`)
fmt.Println(err)

5. 訂閱消息

// 訂閱消息
var subscribes = []func(){
    // 直接寫方法
    func() {
        ClientSubscribe("topic/subscribe/example", 1, func(c mqtt.Client, msg mqtt.Message) {
            fmt.Println("subscribe Msg:", string(msg.Payload()))
        }, func(err error) {
            fmt.Println(err.Error())
        })
    },
    // 調(diào)用
    subscribeExample2,
}

func subscribeExample2() {
    ClientSubscribe("topic/subscribe/example2", 1, func(c mqtt.Client, msg mqtt.Message) {
        fmt.Println("subscribe Msg2:", string(msg.Payload()))
    }, func(err error) {
        fmt.Println(err.Error())
    })
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容