本文采用mica-mqtt进行编写消息订阅客户端
1.引入依赖
| <dependency> |
| <groupId>net.dreamlu</groupId> |
| <artifactId>mica-mqtt-client-spring-boot-starter</artifactId> |
| <version>2.0.3</version> |
| </dependency> |
2.配置信息(可在application.yml或nacos中配置,本文案例是配置到nacos中)
| mqtt: |
| client: |
| enabled: true |
| ip: 118.195.255.66 |
| port: 1883 |
| name: Mica-Mqtt-Client |
| clientId: 000001 |
| user-name: mica |
| password: 123456 |
| timeout: 5 |
| reconnect: true |
| re-interval: 5000 |
| version: mqtt_3_1_1 |
| read-buffer-size: 8KB |
| max-bytes-in-message: 10MB |
| buffer-allocator: heap |
| keep-alive-secs: 60 |
| clean-session: true |
| ssl: |
| enabled: false |
| keystore-path: |
| keystore-pass: |
| truststore-path: |
| truststore-pass: |
3.编写连接mqtt服务端的类
| import lombok.extern.slf4j.Slf4j; |
| import org.springframework.beans.factory.annotation.Autowired; |
| import org.springframework.context.annotation.Configuration; |
| import org.springframework.context.event.EventListener; |
| |
| @Configuration |
| @Slf4j |
| public class MqttClientConnectListener { |
| |
| @Autowired |
| private MqttClientCreator mqttClientCreator; |
| |
| @EventListener |
| public void onConnected(MqttConnectedEvent event) { |
| log.info("MqttConnectedEvent:{}", event); |
| } |
| |
| @EventListener |
| public void onDisconnect(MqttDisconnectEvent event) { |
| |
| log.info("MqttDisconnectEvent:{}", event); |
| |
| mqttClientCreator.clientId("mattx_f8e93bef" + System.currentTimeMillis()) |
| .username("admin") |
| .password("888888"); |
| } |
| |
| } |
4.订阅消息
| import net.dreamlu.iot.mqtt.codec.ByteBufferUtil; |
| import net.dreamlu.iot.mqtt.codec.MqttQoS; |
| import net.dreamlu.iot.mqtt.spring.client.MqttClientSubscribe; |
| |
| import java.nio.ByteBuffer; |
| |
| @Configuration |
| @Slf4j |
| public class MqttClientSubscribeListener { |
| @MqttClientSubscribe(value = "topic1", qos = MqttQoS.AT_MOST_ONCE) |
| public void subQos1(String topic, ByteBuffer payload) { |
| log.info("topic:{} payload:{}", topic, ByteBufferUtil.toString(payload)); |
| String msg = ByteBufferUtil.toString(payload); |
| JSONObject jsonObject = JSONObject.parseObject(msg); |
| } |
| } |
5.可写一个发布方法进行测试
| @Service |
| @Slf4j |
| public class ClientService { |
| @Autowired |
| private MqttClientTemplate client; |
| |
| public boolean publish(String body) { |
| client.publish("topic1", body.getBytes(StandardCharsets.UTF_8)); |
| return true; |
| } |
| } |
mqttx-客户端工具
可用mqttx工具查看接收和发送的数据情况

【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战