Java中Spring Boot使用MQTT推送,订阅

Java中Spring Boot使用MQTT推送,订阅


推荐大家尝试 MQTT-Macchiatto ,轻松实现优雅的 MQTT 连接体验。快速简便 ,让你的代码更加优雅

GitHub | Gitee

在 pom.xml 中引入 Introduce us in pom.xml
xml 复制代码
<dependency>
    <groupId>io.github.rururunu</groupId>
    <artifactId>MQTT-Macchiatto</artifactId>
    <version>0.1.2</version>
</dependency>
📝 配置 to configure

在 application.yml 中编写配置 Write configuration in application.yml:

yaml 复制代码
mto-mqtt:
    # 主机
    host: tcp://${ip}:${port}
    # 用户名
    username: ${username}
    # 密码
    password: ${password}
    # 超时时间
    timeout: 10000
    # 心跳
    keepalive: 60
    # 重连间隔
    reconnect-frequency-ms: 5000

启动类上添加 Add to Startup Class

java 复制代码
@SpringBootApplication(scanBasePackages = {"io.github.rururunu"})
监听 Monitor
java 复制代码
MqttPut.of("rsp/")
    .response((topic, message) -> {
        // 在这里编写收到消息的响应操作
        // Write the response operation for receiving messages here
        System.out.println("topic:" + topic + "message:" + message);
    }).start();

或 or

java 复制代码
MqttPut.of()
    .setTopic("topic")
    .setServiceId("serviceId")
    .setCleanSession(true)
    .response((message) -> {
        // 在这里编写收到消息的响应操作
        // Write the response operation for receiving messages here
    })
    .start();

或 or

java 复制代码
MQTTMonitor mqttMonitor = new MQTTMonitor();
mqttMonitor.setClientId("clientId");
mqttMonitor.setCleanSession(false);
mqttMonitor.setQos(MQTTQos.EXACTLY_ONCE);
mqttMonitor.setMqttCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable throwable) {
                    // 编写异常断开的代码
                    // Write code for abnormal disconnection
                    // 可以直接使用封装好的 mqttMonitor.reconnect();
                    // You can directly use the packaged product
                    mqttMonitor.reconnect();
                }

                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                           // 在这里编写收到消息的响应操作
                           // Write the response operation for receiving messages here
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                }
});
// 开启订阅
//Activate subscription
mqttMonitor.start("topic");
上报 Report

使用 init 直接创建 MqttPush 对象来上报

java 复制代码
MqttPush mqttPush = new MqttPush().init();
mqttPush.push("test/", "test", MQTTQos.AT_LEAST_ONCE);

或者你也可以使用 start 来初始化,或更改 MqttPush 信息后重新初始化

java 复制代码
MqttPush mqttPush = new MqttPush();
mqttPush.start();
mqttPush.push("test/", "test", MQTTQos.AT_LEAST_ONCE,
	(iMqttToken) -> System.out.println("success"),
	(iMqttToken, throwable) -> System.out.println("failure")
);

或者您可以使用 MqttReport 来上报

java 复制代码
// 创建连接
// Create connection
MQTTReport mqttReport = new MQTTReport();
mqttReport.setTopic("topic");
mqttReport.setServiceId("serviceId");
mqttReport.setCleanSession(false);
mqttReport.start();
// 发送消息
// send message
mqttReport.getMessage().setQos(MQTTQos.EXACTLY_ONCE.getValue());
mqttReport.getMessage().setPayload("hello".getBytes());
mqttReport.publish(mqttReport.getMqttTopic(), mqttReport.getMessage());

或 or

java 复制代码
// 创建连接
// Create connection
MQTTReport mqttReport = new MQTTReport();
mqttReport.setTopic("topic");
mqttReport.setServiceId("serviceId");
mqttReport.start();
// 发送消息
// Create connection
MqttMessage message = new MqttMessage();
message.setQos(MQTTQos.EXACTLY_ONCE.getValue());
message.setPayload("hello".getBytes());
mqttReport.publish("topic", message);

🪢 自定义 MQTT 服务信息

如果可以通过其他方式获取MQTT 服务的信息,可以省略配置信息,直接通过构建MQTT 服务信息来进行消息的监听和上报,也可以通过创建多个对象来连接不同的 MQTT 服务

If information about MQTT services can be obtained through other means, configuration information can be omitted and messages can be monitored and reported directly by building MQTT service information. Multiple objects can also be created to connect different MQTT services

自定义MQTT 服务监听 Custom host monitoring
java 复制代码
MqttPut.of("test/")
        .host("tcp://127.0.0.1:1883")
        .username("username")
        .password("password")
        .timeout(10000)
        .keepalive(60)
        .cleanSession(false)
        .reconnectFrequencyMs(5000)
        .response((topic, msg) -> System.out.println(topic + ":" + msg))
        .start();
自定义MQTT 服务上报 Custom host reporting
java 复制代码
// 使用 builder 初始化主机信息并使用 init 加载 
// Initialize host information using builder and load it using init
MqttPush mqttPush = new MqttPush.builder()
            .host("tcp://127.0.0.1:1883")
            .username("username")
            .password("password")
            .timeout(10000)
            .keepalive(60)
            .cleanSession(false)
            .build()
            .init((e) -> {
                System.out.println("Mqtt Creation failed" + e);
            });
// 上报消息
// Report message
mqttPush.push("test/", "test", MQTTQos.AT_LEAST_ONCE,
                (iMqttToken) -> System.out.println("success"),
                (iMqttToken, throwable) -> System.out.println("failure")
        );

或 or

java 复制代码
// 初始化主机信息
// Initialize host information
MqttPush mqttPush = new MqttPush()
                 .host("tcp://127.0.0.1:1883")
                 .username("username")
                 .password("password")
                 .timeout(10000)
                 .keepalive(60)
                 .cleanSession(false)
                 .reconnectFrequencyMs(5000);
// 开启主机
// Open the host
mqttPush.start();
// 创建主题 可以忽略这一步,若topic没有创建在调用 push方法时会自动创建一个 topic 的 MqttTopic 对象放入内存
// found topic You can ignore this step. If the topic is not created,
// an MqttTopic object for the topic will be automatically created and placed
// in memory when calling the push method
mqttPush.foundTopic("test/");
// 上报消息
// Report message
mqttPush.push("test/", "test", MQTTQos.AT_LEAST_ONCE,
                 (iMqttToken) -> System.out.println("success"),
                 (iMqttToken, throwable) -> System.out.println("failure")
);
// 可以选择手动关闭
MqttPush.stop();
相关推荐
CryptoPP17 分钟前
使用WebSocket实时获取印度股票数据源(无调用次数限制)实战
后端·python·websocket·网络协议·区块链
白宇横流学长23 分钟前
基于SpringBoot实现的大创管理系统设计与实现【源码+文档】
java·spring boot·后端
草捏子1 小时前
状态机设计:比if-else优雅100倍的设计
后端
考虑考虑2 小时前
Springboot3.5.x结构化日志新属性
spring boot·后端·spring
涡能增压发动积2 小时前
一起来学 Langgraph [第三节]
后端
sky_ph3 小时前
JAVA-GC浅析(二)G1(Garbage First)回收器
java·后端
涡能增压发动积3 小时前
一起来学 Langgraph [第二节]
后端
hello早上好3 小时前
Spring不同类型的ApplicationContext的创建方式
java·后端·架构
roman_日积跬步-终至千里3 小时前
【Go语言基础【20】】Go的包与工程
开发语言·后端·golang
00后程序员4 小时前
提升移动端网页调试效率:WebDebugX 与常见工具组合实践
后端