mqtt协议订阅消息

发布时间 2023-11-25 13:51:15作者: 山茶花llia

本文采用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               # 是否开启客户端,默认:false 使用到的场景有限,非必要请不要启用
    ip: 118.195.255.66              # 连接的服务端 ip ,默认:127.0.0.1
    port: 1883                  # 端口:默认:1883
    name: Mica-Mqtt-Client      # 名称,默认:Mica-Mqtt-Client
    clientId: 000001            # 客户端Id(非常重要,一般为设备 sn,不可重复)
    user-name: mica             # 认证的用户名
    password: 123456            # 认证的密码
    timeout: 5                  # 超时时间,单位:秒,默认:5秒
    reconnect: true             # 是否重连,默认:true
    re-interval: 5000           # 重连时间,默认 5000 毫秒
    version: mqtt_3_1_1         # mqtt 协议版本,可选 MQTT_3_1、mqtt_3_1_1、mqtt_5,默认:mqtt_3_1_1
    read-buffer-size: 8KB       # 接收数据的 buffer size,默认:8k
    max-bytes-in-message: 10MB  # 消息解析最大 bytes 长度,默认:10M
    buffer-allocator: heap      # 堆内存和堆外内存,默认:堆内存
    keep-alive-secs: 60         # keep-alive 时间,单位:秒
    clean-session: true         # mqtt clean session,默认:true
    ssl:
      enabled: false            # 是否开启 ssl 认证,2.1.0 开始支持双向认证
      keystore-path:            # 可选参数:ssl 双向认证 keystore 目录,支持 classpath:/ 路径。
      keystore-pass:            # 可选参数:ssl 双向认证 keystore 密码
      truststore-path:          # 可选参数:ssl 双向认证 truststore 目录,支持 classpath:/ 路径。
      truststore-pass:          # 可选参数:ssl 双向认证 truststore 密码

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) {
        // 离线时更新重连时的密码,适用于类似阿里云 mqtt clientId 连接带时间戳的方式
        log.info("MqttDisconnectEvent:{}", event);
        // 在断线时更新 clientId、username、password
        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工具查看接收和发送的数据情况
image