2016-10-15 08:19


  • paho
  • mqtt

I am using eclipse paho golang library to create new MQTT client for a particular client id:

func CreateMQTTClient(clientID string) (client MQTT.Client) {
    username := viper.GetString("messaging.rabbitmq.username")
    password := viper.GetString("messaging.rabbitmq.password")
    host := viper.GetString("messaging.rabbitmq.host")
    mqqtPort := viper.GetString("messaging.rabbitmq.mqqtPort")
    rabbitMqMQQTURL := "tcp://" + host + ":" + mqqtPort
    opts := MQTT.NewClientOptions().AddBroker(rabbitMqMQQTURL)
    opts.Username = username
    opts.Password = password
    cli := MQTT.NewClient(opts)

    if (!cli.IsConnected()) {
        log.Println("I came here for cli:", clientID)
        if token := cli.Connect(); token.Wait() && token.Error() != nil {

    return cli


I am not sure how do I get this client back using clientId. If I call CreateMQTTClient again, all existing subscriptions are lost.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dox90448 dox90448 5年前

    There is, unfortunately, no way to query an MQTT server to find out what subscriptions it has active for your client id. When you connect with the same client ID as a previous session the server assumes you have the same state as last time you were connected, but there is no way to pre connect a MessageHandler with a topic in the Go client, the only way to add and remove them is with Subscribe/Unsubscribe.

    Assuming the server is working correctly, if you connect as above reusing a client id the server will continue to send you messages according to your previous subscriptions but the Go client doesn't know what to do with them so will invoke the default message handler. The best way to currently resolve this would be to call Subscribe() in the OnConnectHandler, assuming the topics you want to subscribe to are predetermined rather than dynamic.

    点赞 评论 复制链接分享