yuleduiPay/service/mqtt.go

72 lines
1.8 KiB
Go
Raw Normal View History

2024-11-05 17:34:58 +08:00
package service
import (
2024-11-06 15:15:45 +08:00
"encoding/json"
"errors"
2024-11-05 17:34:58 +08:00
"fmt"
"time"
2024-11-06 15:15:45 +08:00
"yuleduiPay/service/vo"
2024-11-05 17:34:58 +08:00
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/guid"
)
type MQTT struct {
2024-11-06 15:15:45 +08:00
client mqtt.Client
2024-11-05 17:34:58 +08:00
}
2024-11-06 15:15:45 +08:00
var MQTTService MQTT
2024-11-05 17:34:58 +08:00
func (t *MQTT) InitMQTT() error {
2024-11-06 15:15:45 +08:00
ip := g.Cfg().MustGet(nil, "MQTT.ip")
port := g.Cfg().MustGet(nil, "MQTT.port")
/*
user := g.Cfg().MustGet(nil, "MQTT.user")
passwd := g.Cfg().MustGet(nil, "MQTT.passwd")
*/
2024-11-05 17:34:58 +08:00
opts := mqtt.NewClientOptions()
2024-11-06 15:15:45 +08:00
mqttAddress := fmt.Sprintf("mqtt://%s:%d", ip.String(), port.Int())
g.Log().Line().Print(nil, "MQTT连接地址:", mqttAddress)
opts.AddBroker(mqttAddress)
2024-11-05 17:34:58 +08:00
opts.SetKeepAlive(time.Hour * 24)
opts.SetPingTimeout(time.Second * 30)
opts.SetClientID(guid.S())
2024-11-06 15:15:45 +08:00
//opts.SetUsername(user.String()) //使用用户名和密码
//opts.SetPassword(passwd.String())
2024-11-07 18:07:35 +08:00
//opts.SetDefaultPublishHandler(messagePubHandler) // 设置消息回调处理函数
2024-11-05 17:34:58 +08:00
//opts.OnConnect = connectHandler
opts.OnConnectionLost = t.connectLostHandler
2024-11-06 15:15:45 +08:00
t.client = mqtt.NewClient(opts)
token := t.client.Connect()
if token.Wait() && token.Error() != nil {
err := errors.New("MQTT初始化失败:" + token.Error().Error())
g.Log().Line().Error(nil, err)
2024-11-05 17:34:58 +08:00
return err
}
return nil
}
// MQTT 推送订单结果消息
2024-11-06 15:15:45 +08:00
func (t *MQTT) Publish(msg *vo.MQTTOrder) error {
msg.MsgId = guid.S()
msg.SendTime = time.Now().Unix()
jsonbytes, err := json.Marshal(msg)
if err != nil {
return err
}
token := t.client.Publish(msg.Topic, 2, false, string(jsonbytes))
tokenOk := token.Wait()
if !tokenOk { //失败,获取错误原因
return token.Error()
2024-11-05 17:34:58 +08:00
}
2024-11-06 15:15:45 +08:00
return nil
2024-11-05 17:34:58 +08:00
}
2024-11-06 15:15:45 +08:00
2024-11-05 17:34:58 +08:00
func (t *MQTT) connectLostHandler(client mqtt.Client, err error) {
2024-11-06 15:15:45 +08:00
token := t.client.Connect()
2024-11-05 17:34:58 +08:00
g.Log().Line().Print(nil, "MQTT 重新连接成功")
token.Wait()
}