一、需求
通过Java集成mqtt来获得设备监控到的数据,并且当设备发送mqtt的topic发生改变时,Java可以动态改变topic来继续监听设备发送的数据。
二、实现
1、新建一个demo数据库并添加几条数据来进行测试
站点设备信息表
存放监听数据表
2、创建一个springboot项目,开始编写Java代码
(1)创建springboot
具体创建过程略,可参考文章使用IDEA创建一个springboot项目 - 码出精彩人生 - 博客园 (cnblogs.com)
(2)配置配置文件
server.port=13010 spring.datasource.url = jdbc:mysql://localhost:3306/iot-mqtt-demo?characterEncoding=utf-8&useSSL=false&zeroDateTimeBehavior=convertToNull spring.datasource.username = root spring.datasource.password = 123456 spring.datasource.driver-class-name = com.mysql.jdbc.Driver spring.datasource.type = com.zaxxer.hikari.HikariDataSource spring.mqtt.url = tcp://127.0.0.1:61613 consumer.client.id = iot_mqtt spring.mqtt.username = admin spring.mqtt.password = password spring.mqtt.completionTimeout = 3000
(3)pom文件导入相关jar包
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.iotmqtt</groupId> <artifactId>iot-mqtt-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> </parent> <dependencies> <!--spring-mqtt--> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-mqtt</artifactId> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-stream</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.0</version> </dependency> <!-- swagger --> <dependency> <groupId>io.springfox</groupId>