登录
首页 >  Golang >  Go问答

设置MQTT连接的超时时间的有效方法

来源:stackoverflow

时间:2024-03-25 09:21:35 137浏览 收藏

在设置 MQTT 连接超时时间时,需要谨慎。虽然将 `ConnectTimeout` 设置为非零值可以防止连接无限期挂起,但将 `ConnectRetry` 设置为 `true` 会导致连接循环尝试,没有错误消息。正确的解决方案是将 `ConnectTimeout` 设置为非零值,并在连接尝试后设置 `ConnectRetry`。这样,连接会在尝试后正确失败,并且如果连接断开,客户端仍会重新连接。

问题内容

我想确保我的程序在无法连接到 mqtt 服务器时会崩溃。为此,我将 connecttimeout 设置为 10 秒,但是当连接到不存在的服务器(名称不存在)时,对 mqtt 的调用会挂起

package main

import (
    "fmt"
    "time"

    mqtt "github.com/eclipse/paho.mqtt.golang"
)

func main() {
    timeout, _ := time.ParseDuration("10s");
    opts := mqtt.NewClientOptions()
    opts.AddBroker("tcp://this.does.not.resolve.example.coooom:1883")
    opts.SetClientID("monitor")
    opts.SetOrderMatters(false)
    opts.SetConnectRetry(true)
    opts.SetConnectTimeout(timeout)
    client := mqtt.NewClient(opts)
    if token := client.Connect(); token.Wait() && token.Error() != nil {
        panic(fmt.Sprintf("cannot connect to MQTT: %v", token.Error()))
    }
}

如何正确设置超时时间?


正确答案


opts.setconnectretry(true) 似乎将连接置于循环中(没有任何错误消息)。通过将代码更改为...

package main

import (
    "fmt"
    "time"

    mqtt "github.com/eclipse/paho.mqtt.golang"
)

func main() {
    timeout, _ := time.ParseDuration("10s");
    opts := mqtt.NewClientOptions()
    opts.AddBroker("tcp://this.does.not.resolve.example.coooom:1883")
    opts.SetClientID("monitor")
    opts.SetOrderMatters(false)
    opts.SetConnectTimeout(timeout)
    client := mqtt.NewClient(opts)
    if token := client.Connect(); token.Wait() && token.Error() != nil {
        panic(fmt.Sprintf("cannot connect to MQTT: %v", token.Error()))
    }
    opts.SetConnectRetry(true)
}

...连接正确失败(并且希望,如果连接断开,客户端仍会重新连接)

编辑:我认为在连接尝试后移动 opts.setconnectretry(true) 不会使其自动重新连接(因为选项已被使用)。这是第 22 条军规的情况。

今天关于《设置MQTT连接的超时时间的有效方法》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>