spring的MQTT 支持
spring-integration的版本为:5.2.1
Spring Integration提供了入站适配器和出站适配器以支持MQTT协议。
你需要在你的项目中加入spring-integration-mqtt依赖:
Maven:
org.springframework.integration
spring-integration-mqtt
5.2.1.RELEASE
Gradle:
compile "org.springframework.integration:spring-integration-mqtt:5.2.1.RELEASE"
当前的实现采用的是Eclipse Paho MQTT Client库。
入站适配器和出站的适配器的配置都是通过DefaultMqttPahoClientFactory实现的。关于更多的配置选项可以查看Paho的文档。
我们推荐你配置一个MqttConnectOptions对象,并把它注入到连接工厂中,而不是在连接工厂中自己设置。
入站(消息驱动)通道适配器
入站适配器是通过MqttPahoMessageDrivenChannelAdapter来实现的。为方便起见,你可以使用命名空间来配置,最小的配置如下:
class="org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory">
client-id="${mqtt.default.client.id}.src"
url="${mqtt.url}"
topics="sometopic"
client-factory="clientFactory"
channel="output"/>
下面这段配置展示了可以用到的属性:
client-id="foo"
url="tcp://localhost:1883"
topics="bar,baz"
qos="1,2"
converter="myConverter"
client-factory="clientFactory"
send-timeout="123"
error-channel="errors"
recovery-interval="10000"
channel="out" />
client-id 客户端id
url broker的地址
topics 此适配器接收消息的主题,以逗号分割
qos 逗号分割的Qos值
converter 此处指的是MqttMessageConverter,可选。默认会使用DefaultPahoMessageConver,此消息转换器会产生一个消息体为字符串的消息,这个消息带有这些头信息:
. mqtt_topic : 消息来自于哪一个topic
. mqtt_duplicate: true,如果此消息为重复消息的话
. mqtt_qos : 消息的Qos
client-factory 客户端工厂
send-timeout 发送的超时时间。它只在通道阻塞时起作用
error-channel 错误通道:下载流的异常会以ErrorMessage的形式被发送到此通道内。消息体为MessagingException
,MessagingException 中包含有失败信息和原因。
recovery-interval 恢复的时间间隔,此选项控制着适配器在失败后重连的间隔时间,默认是10000ms即10s。
注意:
从4.1开始,你可以在上面的配置中省略URL,而只需要在DefaultMqttPahoClientFactory中配置serverURIs 即可。开启这项配置,你可以连接到一个高可用的集群。
从4.2.2开始,如果此适配器成功订阅这些topic,就会生成一个MqttSubscribedEvent 事件。当连接或订阅失败时,会生成一个MqttConnectionFailedEvent事件。只要我们定义一个ApplicationListener的类,就可以接收这些事件。同样,recoveryInterval 此选项控制着适配器在失败后重连的间隔时间,默认是10000ms即10s。
注意:
xxxx
注意:
xxxx
在运行时添加和移除topic
从4.1版本开始,你可以通过程序来修改此适配器订阅的topic。Spring Integration提供了addTopic()和removeTopic()方法。
在添加topic时,你可以指定Qos值(如果不指定的话,默认值是1)。你也可以发送一个带有特定消息体的消息给来修改topic。例如: "myMqttAdapter.addTopic('foo', 1)"。
停止和启动适配器对主体列表不会产生影响(它不会恢复原来在配置中所做的设置)。应用上下文的生命周期之外,这些修改不会被保留下来。一个新的应用上下文会恢复到所做的配置。
在适配器停止时(或与broker断开连接时),修改主题,会在下一次新连接建立时,生效。
使用java进行配置
下面这个示例展示了如何使用java配置入站适配器:
@SpringBootApplication
public class MqttJavaApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(MqttJavaApplication.class)
.web(false)
.run(args);
}
@Bean
public MessageChannel mqttInputChannel() {
return new DirectChannel();
}
@Bean
public MessageProducer inbound() {
MqttPahoMessageDrivenChannelAdapter adapter =
new MqttPahoMessageDrivenChannelAdapter("tcp://localhost:1883", "testClient",
"topic1", "topic2");
adapter.setCompletionTimeout(5000);
adapter.setConverter(new DefaultPahoMessageConverter());
adapter.setQos(1);
adapter.setOutputChannel(mqttInputChannel());
return adapter;
}
@Bean
@ServiceActivator(inputChannel = "mqttInputChannel")
public MessageHandler handler() {
return new MessageHandler() {
@Override
public void handleMessage(Message> message) throws MessagingException {
System.out.println(me