2014-01-21 81 views
2

我開始使用Mqtt,我很難處理一個不可靠的網絡。 我使用Paho Java客戶端(在Groovy中)將消息發佈給遠程的Mosquitto Broker。Mqtt Paho - 試圖發佈,而經紀人無法訪問

當代理不可達時,有沒有辦法讓Paho客戶端持久保留消息並自動重新連接到代理併發布本地存儲的消息?我是否必須親自處理所有事情,例如使用當地的經紀商?

這裏是我的客戶的建築規範

String persistenceDir = config['persistence-dir'] ?: System.getProperty('java.io.tmpdir') 
    def persistence = new MqttDefaultFilePersistence(persistenceDir) 
    client = new MqttAsyncClient(uri, clientId, persistence) 
    client.setCallback(this) 
    options = new MqttConnectOptions() 
    if (config.password) { 
     options.setPassword(config.password as char[]) 
     options.setUserName(config.user) 
    } 
    options.setCleanSession(false) 
    client.connect(options) 

我的發佈代碼

def message = new MqttMessage(Json.encode(outgoingMessage).getBytes()) 
    try { 
    client?.connect(options) 
    def topic = client.getTopic('processMsg') 
    message.setQos(1) 
    def token = topic.publish(message) 
    if (client) { 
     client.disconnect() 
    } 

感謝

回答

2

泛美衛生組織的客戶端將只持續飛行的消息,當它連接到代理。

通常,當連接問題開始來了,你會看到消息超時彈出

  • 超時等待來自服務器(32000)

響應此時消息會仍然堅持。

然而,當連接丟失,你開始看到這個

  • 客戶端未連接(32104)

你應該假設該消息尚未由泛美衛生組織堅持。

可以在org.eclipse.paho.client.mqttv3.internal.ClientComms調試此:

/** 
* Sends a message to the broker if in connected state, but only waits for the message to be 
* stored, before returning. 
*/ 
public void sendNoWait(MqttWireMessage message, MqttToken token) throws MqttException { 
    final String methodName = "sendNoWait"; 
    if (isConnected() || 
      (!isConnected() && message instanceof MqttConnect) || 
      (isDisconnecting() && message instanceof MqttDisconnect)) { 
     this.internalSend(message, token); 
    } else { 
     //@TRACE 208=failed: not connected 
     log.fine(className, methodName, "208"); 
     throw ExceptionHelper.createMqttException(MqttException.REASON_CODE_CLIENT_NOT_CONNECTED); 
    } 
} 

internalSend將持續的消息,但只有當它連接到代理。

還要考慮到Paho可以處理的最大數量的機上消息。如果超過了,它也會決定不堅持這個信息。

0

您可以設置本地代理並與遠程代理橋接。這樣,您可以在本地排隊所有消息,當遠程代理恢復聯機時,所有消息都可以交付。