2015-11-27 113 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第一个选项的限制。