go - 使用 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 的方式有关?任何想法表示赞赏。
解决方案
我设法修复它这是我的新代码:
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())
}()
}
推荐阅读
- vue.js - Vue没有从API中找到图像路径
- c# - Serilog PostgresSql 接收器中的 .NET Core 自定义列
- arduino - 如何从 RFID 卡读取数据,然后通过串行监视器用新数据覆盖它?
- database - 如何在单独的函数中连接到 MongoDB?
- excel - 四舍五入给定的数字
- bash - 如何在bash中使用sed命令替换字符串中的特殊字符
- java - 使用 Selenium/java 将网页保存为 PDF
- reactjs - 反应数组状态不推送值
- jupyter-lab - 无法通过 JupyterLab 中的“从路径打开”打开文件
- c++ - 如何控制过滤器尺寸