2015-11-27 112 views
0

我們決定在我們的移動應用程序中使用mqtt協議作爲聊天模塊。我也想在服務器端保存主題的消息。但我看到,mqtt客戶端在這裏是全球性的,所以有一種方法是我必須訂閱mqtt客戶端的單個實例到所有主題並將消息保存在數據庫中。但是做到這一點是正確的做法。我只是在擔心。Mqtt:服務器端的持久消息

private void buildClient(){ 
     log.debug("Connecting... "+CLIENT_ID); 
     try { 
      mqttClient = new MqttClient(envConfiguration.getBrokerUrl(), CLIENT_ID); 
     } catch (MqttException e) { 
      log.debug("build client stopped due to "+e.getCause()); 
     } 
     chatCallback = new ChatCallback(); 
     mqttClient.setCallback(chatCallback); 
     mqttConnectOptions = new MqttConnectOptions(); 
     mqttConnectOptions.setCleanSession(false); 
    } 

    @Override 
    public void connect() { 
     if(mqttClient == null || !mqttClient.getClientId().equals(CLIENT_ID)){ 
      buildClient(); 
     } 
     boolean tryConnecting = true; 
     while(tryConnecting){ 
      try { 
       mqttClient.connect(mqttConnectOptions); 
      } catch (Exception e) { 
       log.debug("connection attempt failed "+ e.getCause() + " trying..."); 
      } 
      if(mqttClient.isConnected()){ 
       tryConnecting = false; 
      }else{ 
       pause(); 
      } 
     } 
    } 


    @Override 
    public void publish() { 
     boolean publishCallCompletedErrorFree = false; 
     while (!publishCallCompletedErrorFree) { 
      try { 
       mqttClient.publish(TOPIC, "hello".getBytes(), 1, true); 
       publishCallCompletedErrorFree = true; 
      } catch (Exception e) { 
       log.debug("error occured while publishing "+e.getCause()); 
      }finally{ 
       pause(); 
      } 
     } 
    } 

    @Override 
    public void subscribe() { 
     if(mqttClient != null && mqttClient.isConnected()){ 
      try { 
       mqttClient.subscribe(TOPIC, 2); 
      } catch (MqttException e) { 
       log.debug("subscribing error.."+e.getCause()); 
      } 
     } 

    } 

    @Override 
    public void disconnect() { 
     System.out.println(this.mqttClient.isConnected()); 
     try { 
      mqttClient.disconnect(); 
      log.debug("disconnected.."); 
     } catch (MqttException e) { 
      log.debug("erro occured while disconneting.."+e.getCause()); 
     } 
    } 

回答

0

有兩種可能性,如何來解決這個問題:

  • 寫MQTT客戶端訂閱使用通配符(#在MQTT)
  • 寫經紀人插件,做的所有主題爲您工作,具體取決於您使用的代理實施

有一個很好的描述如何實現這兩個選項在HiveMQ website也desc第一個選項的限制。