物联网实战|Spring Boot MQTT平台 |emqx broker实战

物联网实战|Spring Boot MQTT平台 |emqx broker实战

📑 目录

  1. 物联网实战|Spring Boot MQTT平台 |emqx broker实战

1.1 emqx官网

1.2 docker部署emqx

1.2.1 前期准备和权限开通

1.2.2 docker构建emqx broker应用

1.3 spring-boot接入emqx broker

1.3.1 pom依赖

1.3.2 源码

1.3.3 客户端注册部分代码

1.3.4 客户端注册信息

1.3.5 订阅部分代码

1.3.6 emqx 模拟下发

1.3.7 操作

EMQX 是一款「无限连接,任意集成,随处运行」的大规模分布式物联网接入平台 基于版本6.2.2

emqx官网

https://docs.emqx.com/zh/emqx/latest/

docker部署emqx

其中18083 为网页访问端口 (http://127.0.0.1:28084/#/dashboard/overview)

  • 账号

默认为 admin/public

前期准备和权限开通

bash

复制代码
mkdir -p /data/emqx/
chmod -R 777 /data/

docker构建emqx broker应用

bash

复制代码
  docker run -d   \
  --name emqx   \
  --restart always   \
  -p 1883:1883   \
  -p 8083:8083   \
  -p 8084:8084   \
  -p 8883:8883   \
  -p 28084:18083  \
  -p 18085:18085   \
  -v /data/emqx/data:/opt/emqx/data   \
  -v /data/emqx/log:/opt/emqx/log   \
  -e EMQX_COPY_CONF=true   \
  emqx/emqx:latest

spring-boot接入emqx broker

pom依赖

xml

复制代码
<class="tk-tag">dependencies>
    <!-- HiveMQ MQTT5 客户端(同时兼容 MQTT3.1.1) -->
    <class="tk-tag">dependency>
        <class="tk-tag">groupId>com.hivemq</class="tk-tag">groupId>
        <class="tk-tag">artifactId>hivemq-mqtt-client</class="tk-tag">artifactId>
        <class="tk-tag">version>1.3.15</class="tk-tag">version>
    </class="tk-tag">dependency>
</class="tk-tag">dependencies>

<class="tk-tag">dependencyManagement>
    <class="tk-tag">dependencies>
        <!-- Spring Boot Starter -->
        <class="tk-tag">dependency>
            <class="tk-tag">groupId>org.springframework.boot</class="tk-tag">groupId>
            <class="tk-tag">artifactId>spring-boot-dependencies</class="tk-tag">artifactId>
            <class="tk-tag">version>3.5.11</class="tk-tag">version>
            <class="tk-tag">type>pom</class="tk-tag">type>
            <class="tk-tag">scope>import</class="tk-tag">scope>
        </class="tk-tag">dependency>
    </class="tk-tag">dependencies>
</class="tk-tag">dependencyManagement>

源码

https://gitee.com/kcnf-iot/iot-sample/tree/master/emqx

客户端注册部分代码

java

复制代码
package com.jysemel.iot.client;

import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient;
import com.hivemq.client.mqtt.mqtt5.Mqtt5Client;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;

@Slf4j
@Configuration
public class MqttConfig {

    @Bean
    public Mqtt5AsyncClient mqtt5AsyncClient() {
        // 使用 Builder 模式创建异步客户端
        Mqtt5AsyncClient client = Mqtt5Client.builder()
                .identifier("client" + UUID.randomUUID()) // 设置客户端ID,需唯一
                .serverHost("192.168.0.19") // Broker 地址
                .serverPort(1883) // 默认非加密端口
                .buildAsync(); // 构建异步客户端

        // 连接到 Broker
        client.connect()
                .whenComplete((connAck, throwable) -> {
                    if (throwable != null) {
                        System.err.println("MQTT 连接失败: " + throwable.getMessage());
                        // 可以在这里添加重试逻辑
                    } else {
                        System.out.println("MQTT 连接成功!");
                    }
                });
        return client;
    }
}

客户端注册信息

订阅部分代码

java

复制代码
package com.jysemel.iot.client;

import com.hivemq.client.mqtt.datatypes.MqttQos;
import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Service
public class MqttSubscribeService {

    @Autowired
    private Mqtt5AsyncClient mqttClient;

    // 使用 @PostConstruct 在 Bean 初始化后自动订阅
    @PostConstruct
    public void subscribe() {
        String topic = "server/v1/test";
        mqttClient.subscribeWith()
                .topicFilter(topic) // 订阅的主题
                .qos(MqttQos.AT_LEAST_ONCE)
                .callback(publish -> {
                    // 处理收到的消息
                    String payload = new String(publish.getPayloadAsBytes(), StandardCharsets.UTF_8);
                    System.out.println("收到消息,主题: " + publish.getTopic() + ", 内容: " + payload);
                })
                .send()
                .whenComplete((subAck, throwable) -> {
                    if (throwable != null) {
                        System.err.println("订阅失败: " + throwable.getMessage());
                    } else {
                        System.out.println("订阅主题 'test/topic' 成功!");
                    }
                });
    }
}

emqx 模拟下发

json

复制代码
{ "msg": "hello" }

操作

相关推荐
光依旧4 小时前
MCP实战手记系列(十):MCP Server高可用实战
spring boot·高可用·nginx负载均衡·redis哨兵·mcp·微服务容错·resilience4j熔断
Joy T4 小时前
Spring AI 项目中的 pom.xml、application.yml 与 Nacos:从依赖管理到运行配置
spring·nacos·pom.xml·profile·参数配置·application.yml
省钱兄--zs7 小时前
西安24小时自助健身房解决方案实战:系统开发与部署全流程指南
java·spring boot·系统架构·intellij-idea·需求分析
ly76899 小时前
Spring Boot 集成 Elasticsearch 的生产实践:客户端选型、索引生命周期与批量写入容错
spring boot·elasticsearch·索引生命周期·java api client·批量写入
程序猿_极客9 小时前
【免费】分享一套优质的基于SpringBoot的服装商城管理系统的设计与实现(带可视化图表、协同过滤功能),源码+文档+视频详解(讲解)
java·spring boot·后端·服装商城管理系统
bug菌10 小时前
🤔同事突然问我:Spring的注解 @Component 和 @Service 有何不同?
java·spring boot·后端
Lonely丶墨轩11 小时前
用 Vue + Spring Boot + Python 做一个 AI 双人海龟汤游戏:从出题、联机到自动审稿等核心技术设计与实现
spring boot·后端·游戏
fundoit11 小时前
为什么需要 Access Token 和 ID Token 两个令牌
java·spring·架构·github·oauth2
鱼宵11 小时前
Spring AI 流式输出:Flux + SSE 打字机,回答不再干等三秒
java·人工智能·spring·sse·springai·流式输出
她的男孩12 小时前
打印模板草稿能保存,一点发布就报主从关系:我们把校验拆成了两档
java·spring boot·后端