Search code examples
spring-integrationmqttmosquitto

Spring Mqtt integration: outbound topic issue


Hi I'm trying to use spring integration to receive MQTT messages, process them and publish to another topic.

Here is the integration.xml:

   <int-mqtt:outbound-channel-adapter id="mqtt-publish"
    client-id="spring-foo-1"
    client-factory="clientFactory"
    auto-startup="true"
    url="tcp://localhost:1883"
    default-qos="0"
    default-retained="true"
    default-topic="tweets/akki" />

   <int-mqtt:message-driven-channel-adapter id="oneTopicAdapter"
    client-id="spring-foo-2"
    client-factory="clientFactory"
    auto-startup="true"
    url="tcp://localhost:1883"
    topics="mqtt/publish"
    />

    <int:service-activator input-channel="oneTopicAdapter" method="logMessages" ref="mqttLogger" output-channel="mqtt-publish"></int:service-activator>

    <bean id="mqttLogger" class="hello.mqttReceiver" />

And mqttReceiver.java:

package hello;
public class mqttReceiver {
   public String logMessages(String a){
       String processed_data = a; //TODO Process Data
       return processed_data;
   }
}

Following are the issues I'm facing:

  • The processed_data is routed to mqtt/publish and not mqtt/akki
  • The processed_data is not published ones but many times

Solution

  • That's correct because the AbstractMqttMessageHandler takes a look first of all into headers:

    String topic = (String) message.getHeaders().get(MqttHeaders.TOPIC);
        Object mqttMessage = this.converter.fromMessage(message, Object.class);
        if (topic == null && this.defaultTopic == null) {
            throw new MessageHandlingException(message,
                    "No '" + MqttHeaders.TOPIC + "' header and no default topic defined");
        }
    

    When the DefaultPahoMessageConverter populates that MqttHeaders.TOPIC header from the MqttPahoMessageDrivenChannelAdapter on message arrival.

    You should consider to use <int:header-filter header-names="mqtt_topic"/> before sending message to the <int-mqtt:outbound-channel-adapter>