MQTT Support

Java MQTT 代码例子 MQTT Support :: Spring Integration <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-mqtt</artifactId> <version>6.2.1</version> </dependency> 阅读详情
24. MQTT Support
Prev Part V. Integration Endpoints Next

24. MQTT Support

24.1 Introduction

Spring Integration provides inbound and outbound channel adapters supporting the MQ Telemetry Transport (MQTT) protocol. The current implementation uses the Eclipse Paho MQTT Client library.

Configuration of both adapters is achieved using the DefaultMqttPahoClientFactory. Refer to the Paho documentation for more information about configuration options.

[Note]

It is preferred to configure an MqttConnectOptions object and inject it into the factory, instead of setting the (deprecated) options on the factory itself.

24.2 Inbound (message-driven) Channel Adapter

The inbound channel adapter is implemented by the MqttPahoMessageDrivenChannelAdapter. For convenience, it can be configured using the namespace. A minimal configuration might be:

<bean id="clientFactory"
        class="org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory">
    <property name="connectionOptions">
        <bean class="org.eclipse.paho.client.mqttv3.MqttConnectOptions">
            <property name="userName" value="${mqtt.username}"/>
            <property name="password" value="${mqtt.password}"/>
        </bean>
    </property>
</bean>

<int-mqtt:message-driven-channel-adapter id="mqttInbound"
    client-id="${mqtt.default.client.id}.src"
    url="${mqtt.url}"
    topics="sometopic"
    client-factory="clientFactory"
    channel="output"/>

Attributes:

<int-mqtt:message-driven-channel-adapter id="oneTopicAdapter"
    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" />

1

The client id.

2

The broker URL.

3

A comma delimited list of topics from which this adapter will receive messages.

4

A comma delimited list of QoS values. Can be a single value that is applied to all topics, or a value for each topic (in which case the lists must the same length).

5

An MqttMessageConverter (optional). The default DefaultPahoMessageConverter produces a message with a String payload (by default) with the following headers: mqtt_topic - the topic from which the message was received mqtt_duplicate - true if the message is a duplicate mqtt_qos - the quality of service The DefaultPahoMessageConverter can be configured to return the raw byte[] in the payload by declaring it as a <bean/> and setting the payloadAsBytesproperty.

6

The client factory.

7

The send timeout - only applies if the channel might block (such as a bounded QueueChannel that is currently full).

8

The error channel - downstream exceptions will be sent to this channel, if supplied, in an ErrorMessage; the payload is a MessagingException containing the failed message and cause.

9

The recovery interval - controls the interval at which the adapter will attempt to reconnect after a failure; it defaults to 10000ms (ten seconds).

[Note]

Starting with version 4.1 the url can be omitted and, instead, the server URIs can be provided in the serverURIs property of the DefaultMqttPahoClientFactory. This enables, for example, connection to a highly available (HA) cluster.

Starting with version 4.2.2, an MqttSubscribedEvent is published when the adapter successfully subscribes to the topic(s). MqttConnectionFailedEvent s are published when the connection/subscription fails. These events can be received by a bean that implements ApplicationListener.

Also, a new property recoveryInterval controls the interval at which the adapter will attempt to reconnect after a failure; it defaults to 10000ms (ten seconds).

[Note]

Prior to version 4.2.3, the client always unsubscribed when the adapter was stopped. This was incorrect because if the client QOS is > 0, we need to keep the subscription active so that messages arriving while the adapter is stopped will be delivered on the next start. This also requires setting the cleanSession property on the client factory to false - it defaults to true.

Starting with version 4.2.3, the adapter will not unsubscribe (by default) if the cleanSession property is false.

This behavior can be overridden by setting the consumerCloseAction property on the factory. It can have values: UNSUBSCRIBE_ALWAYS, UNSUBSCRIBE_NEVER, and UNSUBSCRIBE_CLEAN. The latter (the default) will unsubscribe only if the cleanSession property is true.

To revert to the pre-4.2.3 behavior, use UNSUBSCRIBE_ALWAYS.

[Important]Important

Starting with version 5.0, the topic, qos and retained properties are mapped to .RECEIVED_... headers (MqttHeaders.RECEIVED_TOPIC, MqttHeaders.RECEIVED_QOS, and MqttHeaders.RECEIVED_RETAINED), to avoid inadvertent propagation to an outbound message which (by default) uses the MqttHeaders.TOPIC, MqttHeaders.QOS, and MqttHeaders.RETAINED headers.

24.2.1 Adding/Removing Topics at Runtime

Starting with version 4.1, it is possible to programmatically change the topics to which the adapter is subscribed. Methods addTopic() and removeTopic() are provided. When adding topics, you can optionally specify the QoS (default: 1). You can also modify the topics by sending an appropriate message to a <control-bus/>with an appropriate payload: "myMqttAdapter.addTopic('foo', 1)".

Stopping/starting the adapter has no effect on the topic list (it does not revert to the original settings in the configuration). The changes are not retained beyond the life cycle of the application context; a new application context will revert to the configured settings.

Changing the topics while the adapter is stopped (or disconnected from the broker) will take effect the next time a connection is established.

24.2.2 Configuring with Java Configuration

The following Spring Boot application provides an example of configuring the inbound adapter using Java configuration:

@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(message.getPayload());
            }

        };
    }

}

24.3 Outbound Channel Adapter

The outbound channel adapter is implemented by the MqttPahoMessageHandler which is wrapped in a ConsumerEndpoint. For convenience, it can be configured using the namespace.

Starting with version 4.1, the adapter supports asynchronous sends, avoiding blocking until the delivery is confirmed; application events can be emitted to enable applications to confirm delivery if desired.

Attributes:

<int-mqtt:outbound-channel-adapter id="withConverter"
    client-id="foo"  
    url="tcp://localhost:1883"  
    converter="myConverter"  
    client-factory="clientFactory"  
    default-qos="1"  
    qos-expression="" 
    default-retained="true"  
    retained-expression="" 
    default-topic="bar"  
    topic-expression="" 
    async="false"  
    async-events="false"  
    channel="target" />

1

The client id.

2

The broker URL.

3

An MqttMessageConverter (optional). The default DefaultPahoMessageConverter recognizes the following headers: mqtt_topic - the topic to which the message will be sent mqtt_retained - true if the message is to be retained mqtt_qos - the quality of service

4

The client factory.

5

The default quality of service (used if no mqtt_qos header is found or the qos-expression returns null. Not used if a custom converter is supplied.

6

An expression to evaluate to determine the qos; default headers[mqtt_qos].

7

The default value of the retained flag (used if no mqtt_retained header is found). Not used if a custom converter is supplied.

8

An expression to evaluate to determine the retained boolean; default headers[mqtt_retained].

9

The default topic to which the message will be sent (used if no mqtt_topic header is found).

10

An expression to evaluate to determine the destination topic; default headers['topic'].

11

When true, the caller will not block waiting for delivery confirmation when a message is sent. Default:false (the send blocks until delivery is confirmed).

12

When async and async-events are both true, an MqttMessageSentEvent is emitted, containing the message, the topic, the messageId generated by the client library, the clientId and the clientInstance (incremented each time the client is connected). When the delivery is confirmed by the client library, an MqttMessageDeliveredEvent is emitted, containing the the messageId, clientId and the clientInstance, enabling delivery to be correlated with the send. These events can be received by any ApplicationListener, or by an event inbound channel adapter. Note that it is possible that the MqttMessageDeliveredEvent might be received before the MqttMessageSentEvent. Default: false.

[Note]

Starting with version 4.1 the url can be omitted and, instead, the server URIs can be provided in the serverURIs property of the DefaultMqttPahoClientFactory. This enables, for example, connection to a highly available (HA) cluster.

24.3.1 Configuring with Java Configuration

The following Spring Boot application provides an example of configuring the outbound adapter using Java configuration:

@SpringBootApplication
@IntegrationComponentScan
public class MqttJavaApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context =
                new SpringApplicationBuilder(MqttJavaApplication.class)
                        .web(false)
                        .run(args);
        MyGateway gateway = context.getBean(MyGateway.class);
        gateway.sendToMqtt("foo");
    }

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(new String[] { "tcp://host1:1883", "tcp://host2:1883" });
        options.setUserName("username");
        options.setPassword("password".toCharArray());
        factory.setConnectionOptions(options);
        return factory;
    }

    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutbound() {
        MqttPahoMessageHandler messageHandler =
                       new MqttPahoMessageHandler("testClient", mqttClientFactory());
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic("testTopic");
        return messageHandler;
    }

    @Bean
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

    @MessagingGateway(defaultRequestChannel = "mqttOutboundChannel")
    public interface MyGateway {

        void sendToMqtt(String data);

    }

}

Prev Up Next
23. MongoDb Support Home 25. Redis Support
MQTT学习之mosquitto安装 做MQTT的开发,记录下一些学习过程。 安装包括: 1、RPM安装 2、源码安装 (一)使用RPM安装 安装环境Centos6.4 从下面的链接下载mosquitto的RPM安装包:点击打开链接(http://download.opensuse.org/repositories/home:/oojah:/mqtt/CentOS_CentOS-6/i686/) 运行安装 阅读详情

相关推荐

API Gateway with MQTT support (IOT)

支持 MQTT 的 API 网关(物联网)

suiusoar 109

MQTT协议详解及开发教程(三)MQTT Client工具软件选择及简单测试

推荐一款稳定的基于C编写的MQTT Client开源库《cMQTT》 MQTT协议详解及开发教程(一)MQTT协议概述 MQTT协议详解及开发教程(二)MQTT服务器EMQx搭建 在上一篇文章中,我们使用EMQx搭建了一个MQTT服务器,有了服务器,自然就需要MQTT Client,在协议了解阶段, 我们还是选择别人做好的MQTTclient软件更容易理解MQTT的整个过程,我们以目前常用的MQTTclient软件 MQTT.fx 为例,这个可以在官网下载,也可以在其他网站下载,下载完成...

猪哥的专栏 6273

Docker MQTT安装使用教程

MQTT简介 MQTT(Message Queuing Telemetry Transport,消息队列遥测传输)是IBM开发的一个即时通讯协议,有可能成为物联网的重要组成部分。该协议支持所有平台,几乎可以把所有联网物品和外部连接起来,被用来当做传感器和制动器(比如通过Twitter让房屋联网)的通信协议。 Docker安装RabbitMQ配置MQTT 使用RabbitMQ作为MQTT服务端,Eclipse Paho作为客户端。宿主机系统为ubuntu16.04 Docker下载镜像 docker pull daocloud.io/library/rabbitmq:3.7.4 启动Rabbit

springboot整合mqtt+maven+yml 亲测可用

通过注入 MessageProducerSupport 的实例 MqttPahoMessageDrivenChannelAdapter,实现订阅 Topic 和绑定消息消费的 MessageChannel。DirectChannel 收到消息后,内部通过 MessageHandler 的实例 MqttPahoMessageHandler 发送到指定的 Topic。消息通过消息网关发送出去,由 MessageChannel 的实例 DirectChannel 处理发送的细节。免费版限本地 可用通过端口转发。

qq_35757427的博客 685

Docker一键部署Synopsys EDA全家桶(VCS/Verdi 2018版)保姆级教程

本文提供了一份详尽的Docker容器化部署Synopsys EDA工具链(VCS/Verdi 2018版)的保姆级教程。通过环境隔离与标准化,解决传统安装的依赖冲突问题,并重点攻克了容器内GUI图形界面显示的核心难题。教程涵盖从Docker基础安装、镜像获取、容器启动配置,到使用X11转发或VNC实现Verdi完美显示的完整实践,旨在帮助芯片设计工程师快速构建稳定、可移植的一键化EDA工作环境。

weixin_29281941的博客 198

逆向实战:基于内存态匿名段分析的 DexProtector 检测绕过策略

本文深入探讨了针对DexProtector加固方案的Frida检测绕过策略。通过分析运行时动态加载到匿名内存段的核心检测逻辑,提出了一套基于内存态分析、定位并转储匿名可执行段,进而通过精准Hook与“等式化替换”等技术实现稳定绕过的实战方法。该方法不仅适用于DexProtector,也对采用类似内存隐藏技术的加固方案具有参考价值。

ik678901的博客 516

springBoot整合mosquitto MQTT服务接收和发送

springboot 整合 moquitto MQTT服务接收和发送

lixiaoyu123456的博客 5747

MacOS M芯片部署ComfyUI:从环境排雷到插件生态一站式指南

本文为MacOS M系列芯片用户提供了一份详尽的ComfyUI部署指南。文章深入剖析了因架构差异导致的常见安装报错根源,并给出了基于MPS后端的正确PyTorch安装命令。从创建纯净Python虚拟环境、分步安装依赖,到验证GPU加速,手把手指导完成部署。同时,还推荐了包括管理器、汉化在内的必备插件,以完善使用生态,帮助用户一站式解决从环境搭建到效率提升的所有问题。

weixin_29261711的博客 995

Jmeter 测试 MQ 接口怎么做?跟我学秒变大神!_jmeter测试队列(2)

添加 MQTT Subscriber 在 Provider URL 地址中,填写你的服务器 ip,然后点击右侧的 Generate ID 自动生成 Client ID,然后再在 Topic 中,输入一个主题信息,在 Text Message 中,填写要发布的信息。run 一下,就成功了。安装成功后,在取样器中,添加 WebSocket Open Connection, 协议选择默认的 ws, ip 填写你的服务器 ip 地址,端口默认为 8083,Path 根据你的 MQ 的 socket 地址填写。

2401_84254406的博客 1065

深入解析uncompyle6反编译pyc文件及常见错误修复指南

本文深入解析了使用uncompyle6工具反编译Python字节码文件(.pyc)的完整流程。针对实践中最高频的KeyError和Python版本范围限制两大错误,提供了详细的修复方案与步骤指南,并分享了处理复杂反编译结果的高级技巧与安全实践,是进行代码恢复、调试与分析的重要参考。

uber9的博客 536

Codex 100个真实案例 - 用AI生成Blender 3D建模脚本(建模师要失业了?)

本案例将展示如何用 Codex 生成 Blender Python API(bpy)脚本,自动创建完整的 3D 模型。我们将从基础几何体开始,逐步实现布尔运算、材质设置、光照配置,最终完成一张精美桌子的 3D 建模——包括桌面、桌腿、倒角、木纹材质。还会实现参数化批量生成不同风格的桌子、渲染输出 PNG 图片、以及 360 度旋转动画。全程用自然语言驱动 Codex,让建模从"点鼠标"变成"说人话"!

yueyeguzhuo的专栏 636

【MQTT异常】mqtt.inbound.MqttPahoMessageDrivenChannelAdapter Lost connection: 已断开连接; retrying...

针对原因二的解决方案是如果配置有acl权限,则查询当前登录mqtt用户是否具有订阅对应topic的权限,无权时也会造成一直频繁断线重连,如果没有权限时需要添加上对应的权限。Springboot 集成 MQTT ,在服务端启动后,控制台一直在报 MQTT 已断开连接,在重试中ing。针对原因一的解决方案是在全局使用的clientID保证唯一性,可以采用UUID/时间戳等方式。由于我和同事并行开发,使用的同一套代码,所以我们两个连接MQTT的clientId导致重复。原因二:当前用户没有Topic权限。

No8g攻城狮的博客 5503

LabVIEW实现HTTP通信

本节简要介绍HTTP通信的基础知识,并以工业物联网平台TLINK中云端设备的数据发布设计为例,阐述互联网环境下HTTP客户端应用程序设计的基本方法。重点讲解工业物联网平台TLINK中HTTP设备的创建、通信数据帧的构造与测试。

不脱发的程序猿 1549

IBM MQTT basic information and support platforms

REF:https://www.ibm.com/developerworks/community/groups/service/html/communityview?communityUuid=d5bedadd-e46f-4c97-af89-22d65ffee070 A very small messaging server that uses the lightweight MQTT

纸上得来终觉浅,绝知此事要躬行 1323

北斗导航 | ILS(仪表着陆系统)、MLS(微波着陆系统)和GBAS(地基增强系统)的性能对比

最 早 的 GBAS 系 统 是 **局 域 增 强 系 统(LAAS)**,它是 1990 年由美国 Honeywell 公司 和 NASA 共 同 完 成 的 差 分 GPS(DGPS)演 变 而 来 的。1998 年,LAAS 被 ICAO 采 纳为 GBAS。2009 年 9 月 3 日 Honeywell 公 司 的GBAS 系统通过了 **CAT-I 精密进近着陆系统**的设计认证 ,而 **CAT-II 和 CAT-III 系统的研发和验证工作也正在有序的进行中**

尘世冰封的专栏 3990

蓝牙协议栈详解(3)——BTstack

BTstack是一个轻量级蓝牙协议栈,支持经典蓝牙(BR/EDR)和低功耗蓝牙(BLE)。它采用事件驱动模型,可运行在MCU/CPU上,通过HCI接口与蓝牙控制器通信。协议栈包含完整的蓝牙协议层支持,如L2CAP、RFCOMM、ATT/GATT等,并提供丰富的示例代码。 主要特点包括模块化设计、开源授权、支持多种HCI传输方式(UART/USB)和操作系统适配。开发时需要关注事件驱动编程模型、内存配置优化、HCI传输稳定性等问题。典型应用场景包括SPP串口通信、BLE外设开发等。 使用建议从最小示例开始,逐

嵌入式软硬件叶玄 297

避坑指南:Android集成Paho MQTT库时遇到的`LocalBroadcastManager`错误及解决方案

本文深入分析了Android集成Paho MQTT库时常见的`LocalBroadcastManager`错误,提供了从临时修补到现代化解决方案的多种方法,包括使用AndroidX兼容版本和替代MQTT库,帮助开发者有效解决兼容性问题并优化MQTT通信性能。

weixin_30776273的博客 472

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

Jmeter 测试 MQ 接口怎么做?跟我学秒变大神

好了, 关于 Jmeter 如何调用 MQ 的测试方法,我们就介绍到这。你都掌握了吗?

hlsxjh的博客 830

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

Jmeter 测试 MQ 接口怎么做?

MQ(message queue)消息队列,是基础数据结构 先进先出 的一种典型数据结构。一般用来解决应用解耦,异步消息,流量削锋等问题,实现高性能,高可用,可伸缩和最终一致性架构。MQ 主要产品包括:RabbitMQ、ActiveMQ、RocketMQ、ZeroMQ、KafkaMQTT 是轻量的 (Lightweight)、发布订阅模式 (PubSub) 的物联网消息协议如果已经有 MQTT 环境,环境搭建这一章节,可以跳过。

2301_78276982的博客 3482

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

ibm linux mq 发送消息_JMeter 人人都能学会的 Jmeter 测试 MQ 接口方法

MQTT介绍MQ(message queue)消息队列,是基础数据结构 先进先出 的一种典型数据结构。一般用来解决应用解耦,异步消息,流量削锋等问题,实现高性能,高可用,可伸缩和最终一致性架构。MQ主要产品包括:RabbitMQ、ActiveMQ、RocketMQ、ZeroMQ、KafkaMQTT 是轻量的 (Lightweight)、发布订阅模式 (PubSub) 的物联网消息协议至于现在企业中...

weixin_39946534的博客 633

jmeter 测试 MQ 接口方法

MQTT服务搭建 服务器环境配置: # 安装必须的依赖 sudo yum install -y yum-utils device-mapper-persistent-data lvm2 # 添加稳定的存储库 sudo yum-config-manager --add-repo https://repos.emqx.io/emqx-ce/redhat/centos/7/emqx-ce.repo # 如果低于cento8,可以直接用这一个命令一键安装,centos8则要执行上面的,再执行这句 curl.

u012343977的博客 2922

AndroidX使用Paho MQTT报找不到android/support/v4/content/LocalBroadcastManager

直接自己创建这个类,把androidx.localbroadcastmanager.content.LocalBroadcastManager改改就行。网上有直接引用support-v4包的,但我用的AndroidX,不能为这个类再引用support-v4。虽然奇葩但能解决问题。

wv112406的博客 876

接口里面的方法都是抽象方法吗_JMeter 人人都能学会的 Jmeter 测试 MQ 接口方法...

MQTT介绍MQ(message queue)消息队列,是基础数据结构 先进先出 的一种典型数据结构。一般用来解决应用解耦,异步消息,流量削锋等问题,实现高性能,高可用,可伸缩和最终一致性架构。MQ主要产品包括:RabbitMQ、ActiveMQ、RocketMQ、ZeroMQ、KafkaMQTT 是轻量的 (Lightweight)、发布订阅模式 (PubSub) 的物联网消息协议至于现在企业中...

weixin_39875675的博客 101

手把手教你学Simulink--基于数字孪生与物联网集成的电网系统场景实例:MQTT通信下的电网远程调度管理系统仿真

在智能电网与能源互联网的发展中,传统的调度系统面临通信延迟高、协议不统一、扩展性差等问题。而MQTT(Message Queuing Telemetry Transport)作为一种轻量级、发布/订阅模式✅ 低带宽消耗✅ 高可靠性(QoS 0/1/2)✅ 支持海量设备接入✅ 跨平台兼容性强已成为远程调度系统的理想通信选择。本文将手把手带你使用,构建一个基于MQTT的电网远程调度管理系统调度中心(云端)与变电站(现场)的双向通信实时遥测(电压、电流、功率)远程遥控(开关分合、变压器调档)

MHD0815的博客 579
上一篇: 30分钟学会如何使用Shiro
下一篇: cvc-complex-type.3.2.2: Attribute 'singleton' is not allowed to appear in element 'bean
王树民
博客等级 码龄10年 912粉丝 560原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值