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()))
}
相关推荐
云知谷4 分钟前
【HTML】网络数据是如何渲染成HTML网页页面显示的
开发语言·网络·计算机网络·html
lang201509285 分钟前
Spring Boot 官方文档精解:构建与依赖管理
java·spring boot·后端
lly2024061 小时前
SQL ROUND() 函数详解
开发语言
大宝剑1701 小时前
python环境安装
开发语言·python
why技术1 小时前
从18w到1600w播放量,我的一点思考。
java·前端·后端
lly2024061 小时前
CSS3 多媒体查询
开发语言
间彧1 小时前
Redis Cluster vs Sentinel模式区别
后端
间彧1 小时前
🛡️ 构建高可用缓存架构:Redis集群与Caffeine多级缓存实战
后端
间彧1 小时前
构建本地缓存(如Caffeine)+ 分布式缓存(如Redis集群)的二级缓存架构
后端