[英]Spring integration MQTT publish & subscribe to multiple topics
我正在嘗試構建一個訂閱多個mqtt主題的應用程序,獲取信息,對其進行處理並形成xml,並在處理后觸發一個事件,以便可以將這些事件發送到某個雲服務器,並將成功的響應從那里發送回給mqtt頻道。
<int-mqtt:message-driven-channel-adapter
id="mqttAdapter" client-id="${clientId}" url="${brokerUrl}" topics="${topics}"
channel="startCase" auto-startup="true" />
<int:channel id="startCase" />
<int:service-activator id="startCaseService"
input-channel="startCase" ref="msgPollingService" method="pollMessages" />
<bean id="mqttTaskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="5" />
<property name="maxPoolSize" value="10" />
</bean>
<bean id="msgPollingService" class="com.xxxx.xxx.mqttclient.mqtt.MsgPollingService">
<property name="taskExecutor" ref="mqttTaskExecutor" />
<property name="vendorId" value="${vendorId}" />
</bean>
我的問題是如何將其發布到多個渠道,即是否可以選擇將X消息發布到Y主題。 目前,我有以下內容:
<int:channel id="outbound" />
<int-mqtt:outbound-channel-adapter
id="mqtt-publish" client-id="kj" client-factory="clientFactory"
auto-startup="true" url="${brokerUrl}" default-qos="0"
default-retained="true" default-topic="${responseTopic}" channel="outbound" />
<bean id="eventListner" class="com.xxxx.xxxx.mqttclient.event.EventListener">
<property name="sccUrl" value="${url}" />
<property name="restTemplate" ref="restTemplate" />
<property name="channel" ref="outbound" />
</bean>
我可以這樣發布:
channel.send(MessageBuilder.withPayload("customResponse").build());
我可以做類似的事情嗎?
channel.send(Message<?>, topic)
您的配置看起來不錯。 但是, MessageChannel
是用於松散耦合的抽象,並且僅處理Message
。
因此,您請求a-la channel.send(Message<?>, topic)
對於消息傳遞概念不正確。
但是,我們為您提供了一個竅門。 從AbstractMqttMessageHandler
:
String topic = (String) message.getHeaders().get(MqttHeaders.TOPIC);
.....
this.publish(topic == null ? this.defaultTopic : topic, mqttMessage, message);
因此,您需要的代碼是這樣的:
channel.send(MessageBuilder.withPayload("customResponse").setHeader(MqttHeaders.TOPIC, topic).build());
換句話說,您應該發送帶有mqtt_topic
標頭的Message
,以從<int-mqtt:outbound-channel-adapter>
實現動態發布。
另一方面,我們不建議直接從應用程序使用MessageChannel
。 帶有服務接口的<gateway>
用於最終應用程序。 該topic
可以是標記為@Header(MqttHeaders.TOPIC)
的服務方法參數之一
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.