首页 > 解决方案 > 使用 Goroutine 订阅 MQTT 不打印消息

问题描述

我目前有订阅主题并打印传感器数据的 Go 代码。打印出传感器数据的部分在Goroutine中,但是目前没有打印出任何内容。这是我的代码:

package main

import (
    "fmt"
    MQTT "github.com/eclipse/paho.mqtt.golang"
    "os"
    "os/signal"
    "syscall"
    "sync"
)



var wg sync.WaitGroup

func subscriber(client MQTT.Client, message MQTT.Message) {
    wg.Add(1)
    go func() {
        defer wg.Done()
        fmt.Printf("%s\n", message.Payload())
    }()
}

func main() {

    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)

    opts := MQTT.NewClientOptions().AddBroker("tcp://test.mosquitto.org:1883")

    //opts.SetDefaultPublishHandler(f)
    // Topic to subscribe to for sensor data
    topic := "sensor/data"
    client := MQTT.NewClient(opts)
    if token := client.Connect(); token.Wait() && token.Error() != nil {
        panic(token.Error())
    } else {
        fmt.Printf("Connected to server\n")
    }
    opts.OnConnect = func(c MQTT.Client) {
        //if token := c.Subscribe(topic, 0, f); token.Wait() && token.Error() != nil {
        if token := c.Subscribe(topic, 0, subscriber); token.Wait() && token.Error() != nil {

            panic(token.Error())

        }
    }

    wg.Wait()

    <-c

}

我想知道这是否与我编写 sync.WaitGroup 的方式有关?任何想法表示赞赏。

标签: gomqttgoroutine

解决方案


我设法修复它这是我的新代码:

var wg sync.WaitGroup
// All messages are handled here - printing published messages and publishing new messages
var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {

wg.Add(1)
    go func() {
        defer wg.Done()
        fmt.Printf("%s\n", msg.Payload())
    }()

}

推荐阅读