eclipse-paho / paho.mqtt.golang

Other
2.77k stars 534 forks source link

How to correctly re-subscribe to topic after connection lost #633

Closed MarioRossi37 closed 1 year ago

MarioRossi37 commented 1 year ago

I have to find a way to re-subscribe to topics after connection lost. Currently I have something like this:

// [Other Code...]
opts := mqtt.NewClientOptions()
opts.AddBroker(fmt.Sprintf("%s:%d", brokerAddress, brokerPort))
opts.SetClientID(clientID)
opts.SetTLSConfig(tlsConfig)

opts.AutoReconnect = true
opts.OnConnect = connectHandler
opts.OnConnectionLost = connectLostHandler
opts.CleanSession = true

client = mqtt.NewClient(opts)

if token := client.Connect(); token.Wait() && token.Error() != nil {
    return nil, token.Error()
} else {
    return &MqttClient{client}, nil
}
// [Other Code...]

and then on the onConnect handler something similar to

if token := c.Subscribe(topic1, 1, messageHandler1); token.Wait() && token.Error() != nil {
    log.Fatal(token.Error())
        return
}
if token := c.Subscribe(topic2, 1, messageHandler2); token.Wait() && token.Error() != nil {
    log.Fatal(token.Error())
    return
}

That way if the device loses connection and then resumes it, entering the onConnect should re-subscribe to the topics.

However, what happens if the subscription fails? I would like to automatically retry to subscribe (and not just log the error). What is the correct way to achieve this?

MattBrittan commented 1 year ago

Please ask this kind of question in one of the resources shown in the readme. You need to consider what could lead to a failure and whether you want to retry (if the broker returns an error then it's likely you will get the same error on repeat attempts). The most likely cause of failure is probably a network issue, but if that happens the client will reconnect, so your current code will retry...

MattBrittan commented 1 year ago

Closing this as it's something best discussed elsewhere (and not really an issue specific to this particular client).