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()))
}
相关推荐
FfHUCisI1 分钟前
Golang 切片扩容策略
开发语言·数据库·golang
IT_陈寒1 分钟前
Redis Pipeline用错竟比不用还慢,这个坑我帮你踩过了
前端·人工智能·后端
en.en..3 分钟前
Ubuntu嵌入式开发 export环境变量
java·开发语言·数据库
ynchyong15 分钟前
JavaScript Promise 实战:.then() 与 .catch() 的区别及回调函数封装指南
开发语言·javascript·ecmascript·promise·then
名字还没想好☜18 分钟前
Go 1.21 context.WithoutCancel 实战:父 context 取消了,收尾任务还要继续跑
开发语言·后端·golang·go
源代码•宸37 分钟前
前置准备:定时微服务有什么价值
经验分享·后端·微服务·云原生·架构
wdfk_prog42 分钟前
canopennode-rtt推荐,不只可以做从站,也可以承担主站角色
c语言·开发语言·数据库·学习·算法·深度优先
catino1 小时前
高并发详解
后端
启观川1 小时前
Python基础-第 16 章 综合案例:客户信息管理系统
开发语言·笔记·python·正则表达式
掘金者阿豪1 小时前
GPT-6 Astra 来了,GPT-5.6 Sol 还值得用吗?聊聊 Coding、百万上下文、价格和 Plus/Pro
前端·后端