我已经在使用 Spring Integration 4.1.0 SNAPSHOT。
我有这个 MQTT 出站适配器:
<int-mqtt:outbound-channel-adapter
async="true"
async-events="true"
id="mqttOutput"
channel="httpInputChannel"
client-id="#{controller.mqttPublisherConfig.clientID}"
url="#{controller.mqttPublisherConfig.completeURL}"
default-qos="#{controller.mqttPublisherConfig.qosString}"
default-retained="#{controller.mqttPublisherConfig.retainFlag}"
default-topic="#{controller.mqttPublisherConfig.topic}"
/>
现在在我的 Controller (MVC 应用程序)中,我想接收适配器发出的事件。
我正在实现ApplicatinListener:
@Controller
public class ServletController implements ApplicationListener {
public void onApplicationEvent(ApplicationEvent event)
{
//
}
...
}
仍然,我没有从 MQTT 适配器收到任何事件。
不过,实现 in-event:inbound-channel-adapter 是有效的:
<int-event:inbound-channel-adapter channel="eventLogger"
error-channel="eventErrorChannel"
/>
但我真的很想在代码中处理事件!
最佳答案
您的 @Controller
是否与 MQTT 适配器位于同一应用程序上下文中?或者(这是最常见的), Controller 位于 Web(DispatcherServlet
's)上下文中,而其他 bean 位于由 ContextLoaderListener
加载的根应用程序上下文中。
问题是根上下文中的 bean 无法“看到”servlet 上下文中的 bean,并且子上下文中的监听器不会接收根上下文中发布的事件。
您必须颠覆这个可见性问题 - 要么将业务 bean 移动到 Web 上下文中(通常不推荐,但对于小型应用程序来说并不可怕),或者以某种方式将监听器从根上下文连接到 Controller - 也许通过接线它进入 Controller 并让 Controller 在初始化期间将其自身传递给监听器 (afterPropertiesSet()
)。你会遇到一个类困惑(相互依赖),但它应该可以工作。
顺便说一下,ApplicationListener
可以采用泛型,所以
public class MyListener implements ApplicationListener<MqttIntegrationEvent> { ... }
只会获取 MQTT 事件。
编辑:
另一个解决方案是使用事件 channel 适配器并将 outbound-channel-adapter
添加到 Web 上下文(与 Controller 相同的上下文)...
@Controller
...
public void onMqttEvent(MqttIntegrationEvent event) { ... }
<int:outbound-channel-adapter channel="eventLogger"
ref="myController" method="onMqttEvent" />
它将在根上下文中看到 channel 。
请务必将事件适配器配置为仅接收 MqttIntegrationEvent
。
关于java - Spring 从 MQTT 出站 channel 适配器获取事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24864836/