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()))
}
相关推荐
三体世界2 分钟前
TCP传输控制层协议深入理解
linux·服务器·开发语言·网络·c++·网络协议·tcp/ip
kangkang-5 分钟前
PC端基于SpringBoot架构控制无人机(二):MavLink协议
java·spring boot·后端·无人机
随心点儿23 分钟前
使用python 将多个docx文件合并为一个word
开发语言·python·多个word合并为一个
不学无术の码农27 分钟前
《Effective Python》第十三章 测试与调试——使用 Mock 测试具有复杂依赖的代码
开发语言·python
tomcsdn3133 分钟前
SMTPman,smtp的端口号是多少全面解析配置
服务器·开发语言·php·smtp·邮件营销·域名邮箱·邮件服务器
EnigmaCoder37 分钟前
Java多线程:核心技术与实战指南
java·开发语言
麦兜*1 小时前
Spring Boot秒级冷启动方案:阿里云FC落地实战(含成本对比)
java·spring boot·后端·spring·spring cloud·系统架构·maven
喷火龙8号2 小时前
MSC中的Model层:数据模型与数据访问层设计
后端·架构
5ycode2 小时前
dify项目结构说明与win11本地部署
后端·开源
LaoZhangAI2 小时前
GPT-image-1 API如何传多图:开发者完全指南
前端·后端