Reputation: 7517
How can I publish messages with different topics programmatically?
<mqtt:outbound-channel-adapter id="mqttOut"
auto-startup="true"
client-id="foo"
url="tcp://localhost:1883"
client-factory="clientFactory"
default-qos="0"
default-retained="false"
default-topic="bar"
async="true"
async-events="true" />
I tried Spring integration MQTT publish & subscribe to multiple topics, but were not able to configure.
Also tried with MqttPahoMessageHandlerAdapter
which has a publish()
but protected
.
Going with org.eclipse.paho.client.mqttv3.MqttAsyncClient
and org.eclipse.paho.client.mqttv3.MqttCallback
is very easy. But I would like to stick with spring all the way.
Appreciate if somebody can points me to a correct direction.
Upvotes: 2
Views: 3184
Reputation: 121177
You can do that with Spring Integration anyway! Having a lot of EIP components implementation and Spring power on board (injection, SpEL etc,), plus switching on a bit of imagination, we can reach any end-application requirements even without any Java code.
So, <mqtt:outbound-channel-adapter>
allows determine topic
at runtime. Instead of default-topic
you should supply MqttHeaders.TOPIC
MessageHeader
.
So, if you have a requirement to send the same message to several topics, you just build a copy of that message for each topic. The <splitter>
can help us:
<int:splitter input-channel="enricheMessage" output-channel="sendMessage" apply-sequence="false">
<int-groovy:script>
['topic1', 'topic2', 'topic3'].collect {
org.springframework.integration.support.MessageBuilder.withPayload(payload)
.copyHeaders(headers)
.setHeader(org.springframework.integration.mqtt.support.MqttHeaders.TOPIC, it)
.build()
}
</int-groovy:script>
</int:splitter>
sendMessage
can be ExecutorChannel
to achieve the parallel publishing.
UPDATE
You can achieve the same iteration and message enrichment logic with similar Java code using ref
and method
on <splitter>
.
Of course, we can do that even with SpEL , but it will look a bit complex with Collection Projection
.
Upvotes: 2
Reputation: 174494
Declare a <publish-subscribe-channel id="toMqtt" />
; set it as the channel
attribute on each outbound channel adapter; the message will be sent to each adapter.
Upvotes: 2