【发布时间】:2018-06-28 17:56:04
【问题描述】:
我目前有一个 Go 代码,可以订阅和打印发布到某个主题的传感器数据。这是我的代码:
package main
import (
"crypto/tls"
"flag"
"fmt"
//"log"
"os"
"os/signal"
"strconv"
"syscall"
"time"
MQTT "github.com/eclipse/paho.mqtt.golang"
)
func onMessageReceived(client MQTT.Client, message MQTT.Message) {
//fmt.Printf("Received message on topic: %s\nMessage: %s\n", message.Topic(), message.Payload())
fmt.Printf("%s\n", message.Payload())
}
func main() {
//MQTT.DEBUG = log.New(os.Stdout, "", 0)
//MQTT.ERROR = log.New(os.Stdout, "", 0)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
hostname, _ := os.Hostname()
server := flag.String("server", "tcp://test.mosquitto.org:1883", "The full url of the MQTT server to connect to ex: tcp://127.0.0.1:1883")
topic := flag.String("topic", "topic/sensorTemperature", "Topic to subscribe to")
qos := flag.Int("qos", 0, "The QoS to subscribe to messages at")
clientid := flag.String("clientid", hostname+strconv.Itoa(time.Now().Second()), "A clientid for the connection")
username := flag.String("username", "", "A username to authenticate to the MQTT server")
password := flag.String("password", "", "Password to match username")
flag.Parse()
connOpts := MQTT.NewClientOptions().AddBroker(*server).SetClientID(*clientid).SetCleanSession(true)
if *username != "" {
connOpts.SetUsername(*username)
if *password != "" {
connOpts.SetPassword(*password)
}
}
tlsConfig := &tls.Config{InsecureSkipVerify: true, ClientAuth: tls.NoClientCert}
connOpts.SetTLSConfig(tlsConfig)
connOpts.OnConnect = func(c MQTT.Client) {
if token := c.Subscribe(*topic, byte(*qos), onMessageReceived); token.Wait() && token.Error() != nil {
panic(token.Error())
}
}
client := MQTT.NewClient(connOpts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
} else {
fmt.Printf("Connected to %s\n", *server)
}
<-c
}
我不想订阅这样的消息,而是想将订阅的代码部分放在 Goroutine 中。我希望能够致电go func onMessageReceived。如果在c.Subscribe 中调用此函数,我该怎么做?以及如何添加sync.WaitGroup 参数?谢谢。
【问题讨论】:
-
不知道你在问什么——你已经知道如何启动 goroutine 和定义函数参数了,这有什么特别的问题?
-
@Adrian 目前
onMessageReceived在c.Subscribe中作为参数调用。我的问题只是我如何将onMessageReceived称为 Goroutine。抱歉,我是 Go 编程新手。 -
好的,我现在明白了。请参阅我的答案以获取可能的解决方案。