Go-MQTT使用

前言

因为在前端、java中一直使用paho的mqtt所以在go中也继续使用,原理是一致的,使用其他版本框架也是一样的,本文使用paho的进行演示

再次还可以下载一个好用的mqtt桌面链接工具

https://packages.emqx.net/MQTTX/v1.9.7/MQTTX-Setup-1.9.7-x64.exe

集成

uuid是用于生成不重复的uuid的

go 复制代码
go get github.com/eclipse/paho.mqtt.golang
go get -u github.com/satori/go.uuid

创建客户端

go 复制代码
opts := mqtt.NewClientOptions().AddBroker("tcp://broker.hivemq.com:1883")
	opts.SetClientID(uuid.NewV1().String())
	opts.SetUsername("username")
	opts.SetPassword("password")
	// 设置消息处理函数
	opts.SetDefaultPublishHandler(mqttService.Receive)
	c := mqtt.NewClient(opts)
	if token := c.Connect(); token.Wait() && token.Error() != nil {
		panic("mqtt连接失败,请检查地址账号密码!")
	}

订阅、取消订阅主题

go 复制代码
	if token := c.Subscribe(subTopic, 0, nil); token.Wait() && token.Error() != nil {
		fmt.Println("订阅MQTT主题" + subTopic + "失败")
		os.Exit(1)
	}
	fmt.Print("订阅MQTT主题" + subTopic + "成功")
go 复制代码
// 取消订阅
	if token := c.Unsubscribe(subTopic); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
		os.Exit(1)
	}

发布消息

go 复制代码
// Publish 发送到消息到指定的主题,qos为2保证消息不会丢失也不会重复投递,效率略低
func Publish(c mqtt.Client, pubTopic string, text string) {
	token := c.Publish(pubTopic, 2, false, text)
	fmt.Printf("mqtt:当前主题是 [%s];发送消息: [%s] \n", pubTopic, text)
	token.Wait()
}

接收消息

go 复制代码
// Receive 接收 MQTT
func Receive(client mqtt.Client, msg mqtt.Message) {
	fmt.Printf("mqtt: 当前主题是 [%s]; 接收到的信息是 [%s] \n", msg.Topic(), string(msg.Payload()))
}

完整代码

main.go

复制代码
package main

import (
	mqttService "gin_study/mqtt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	uuid "github.com/satori/go.uuid"
	"strconv"
)

func main() {
	// 创建MQTT、客户端
	opts := mqtt.NewClientOptions().AddBroker("tcp://broker.hivemq.com:1883")
	opts.SetClientID(uuid.NewV1().String())
	opts.SetUsername("username")
	opts.SetPassword("password")
	// 设置消息处理函数
	opts.SetDefaultPublishHandler(mqttService.Receive)
	c := mqtt.NewClient(opts)
	if token := c.Connect(); token.Wait() && token.Error() != nil {
		panic("mqtt连接失败,请检查地址账号密码!")
	}
	// 订阅主题
	mqttService.Subscribe(c, "test/1")
	// 发布消息
	for i := 0; i < 10; i++ {
		mqttService.Publish(c, "test/1", "测试发布消息"+strconv.Itoa(i))
	}
}

mqttService

复制代码
package mqttService

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

// Subscribe mqtt订阅主题
func Subscribe(c mqtt.Client, subTopic string) {
	if token := c.Subscribe(subTopic, 0, nil); token.Wait() && token.Error() != nil {
		fmt.Println("订阅MQTT主题" + subTopic + "失败")
		os.Exit(1)
	}
	fmt.Print("订阅MQTT主题" + subTopic + "成功")
}

// UnSubscribe mqtt取消订阅主题
func UnSubscribe(c mqtt.Client, subTopic string) {
	// 取消订阅
	if token := c.Unsubscribe(subTopic); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
		os.Exit(1)
	}
}

// Publish 发送到消息到指定的主题,qos为2保证消息不会丢失也不会重复投递,效率略低
func Publish(c mqtt.Client, pubTopic string, text string) {
	token := c.Publish(pubTopic, 2, false, text)
	fmt.Printf("mqtt:当前主题是 [%s];发送消息: [%s] \n", pubTopic, text)
	token.Wait()
}

// Receive 接收 MQTT
func Receive(client mqtt.Client, msg mqtt.Message) {
	fmt.Printf("mqtt: 当前主题是 [%s]; 接收到的信息是 [%s] \n", msg.Topic(), string(msg.Payload()))
}
相关推荐
低调小一10 分钟前
Kotlin 2025–2026 客户端开发路线:语言升级 × 跨端落地 × AI Agent 入门
开发语言·人工智能·kotlin
研☆香20 分钟前
JS中的三种显示弹窗
开发语言·前端·javascript
王夏奇25 分钟前
python中的基础知识点-1
开发语言·windows·python
叫我辉哥e126 分钟前
新手进阶Python:办公看板集成多数据源+ECharts高级可视化
开发语言·python·echarts
猛扇赵四那边好嘴.26 分钟前
Flutter 框架跨平台鸿蒙开发 - 问答社区应用开发教程
开发语言·javascript·flutter·华为·harmonyos
C_心欲无痕29 分钟前
Next.js 路由系统对比:Pages Router vs App Router
开发语言·前端·javascript
LawrenceLan31 分钟前
Flutter 零基础入门(二十二):Text 文本组件与样式系统
开发语言·前端·flutter·dart
kylezhao201937 分钟前
C# 各种类型转换深入剖析
开发语言·c#
派大鑫wink37 分钟前
【Day39】Spring 核心注解:@Component、@Autowired、@Configuration 等
java·后端·spring
hxjhnct39 分钟前
JavaScript 的 new会发生什么
开发语言·javascript