Go 使用mqtt

1、创建一个文件夹,并且使用go modules

        go mod init 其中是你的模块名称,如下


go mod init example.com/myproject

2、安装mqtt扩展

go get github.com/eclipse/paho.mqtt.golang

3、开始写主程序

package main

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"log"
	"os"
	"os/signal"
)

// MessageHandlerFunc 定义一个处理消息的函数类型
type MessageHandlerFunc func(mqtt.Client, mqtt.Message)

// AsyncMessageHandler 异步处理消息的包装器
func AsyncMessageHandler(handler MessageHandlerFunc) mqtt.MessageHandler {
	return func(client mqtt.Client, msg mqtt.Message) {
		go handler(client, msg) // 在新的Goroutine中处理消息
	}
}

func main() {

	opts := mqtt.NewClientOptions().AddBroker("****:8883")
	opts.SetClientID("zhuti")
	// 设置MQTT连接的用户名和密码
	opts.SetUsername("****")
	opts.SetPassword("*****")

	// 自定义消息处理函数
	handleMessage := func(client mqtt.Client, msg mqtt.Message) {
		
		fmt.Printf("Received message on topic %s: %s\n", msg.Topic(), msg.Payload())

		// 在这里添加你的消息处理逻辑s
		// ...
	}

	// 使用自定义的异步消息处理器包装原始处理函数
	asyncHandle := AsyncMessageHandler(handleMessage)

	opts.SetDefaultPublishHandler(asyncHandle)

	client := mqtt.NewClient(opts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		log.Fatalf("Failed to connect to MQTT broker: %v", token.Error())
	}

    // 订阅主题
	topics := []string{"#"}
	for _, topic := range topics {
		if token := client.Subscribe(topic, 0, nil); token.Wait() && token.Error() != nil {
			log.Fatalf("Failed to subscribe to topic %s: %v", topic, token.Error())
		}
		
	}

	fmt.Println("MQTT client is connected and subscribed. Waiting for messages...")

	// 例如,可以监听一个os.Signal来优雅关闭。
	//for i := 0; i < 1000; i++ {
	//	text := fmt.Sprintf("Message %d", i)
	//	token := client.Publish("Lattice/22", 0, false, text)
	//	token.Wait()
	//	time.Sleep(1 * time.Second)
	//}
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill)
	<-c // 阻塞等待信号

	//在收到信号后,可以执行清理操作,如断开MQTT连接
	client.Disconnect(250) // 250是超时时间,单位为毫秒
	fmt.Println("Disconnected from MQTT broker.")

}

你可能感兴趣的:(Go,Mqtt,golang,开发语言,后端)