Java使用MQTT连接北斗接收机

1、引入mqtt依赖

        <!--springboot mqtt-->
        <dependency>
            <groupId>net.dreamlu</groupId>
            <artifactId>mica-mqtt-client-spring-boot-starter</artifactId>
            <version>2.2.6</version>
        </dependency>

2、实现ApplicationRunner类

import net.dreamlu.iot.mqtt.spring.client.MqttClientTemplate;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Component
public class Demo implements ApplicationRunner {
    @Resource
    private MqttClientTemplate mqttTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        while (true) {
            String msg = "解析后的坐标!";
            mqttTemplate.publish("beidou/position", msg.getBytes(StandardCharsets.UTF_8));
            Thread.sleep(1000);
        }
    }
}

3、yml添加mqtt配置

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

4、本地安装mqtt服务

参考地址:https://blog.csdn.net/weixin_41542513/article/details/134328627

4、下载MQTTX客户端进行测试

MQTTX:https://mqttx.app/zh

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值