Spring boot mqtt客户端

1 篇文章 0 订阅
  • 导入依赖包
        <dependency>
            <groupId>org.eclipse.paho</groupId>
            <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
            <version>1.2.0</version>
        </dependency>
  • 编写客户端连接配置类
package com.ha.mqtt.config.mqtt;

import com.ha.common.core.utils.IdUtils;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MqttClientConfig {

    @Value("${ha-config.mqtt.host}")
    private String host;
    @Value("${ha-config.mqtt.username}")
    private String username;
    @Value("${ha-config.mqtt.password}")
    private String password;
    @Value("${ha-config.mqtt.topic}")
    private String topic;

    private MqttClient client = null;

    private MqttAsyncClient mqttAsyncClient = null;

    @Bean
    public void initMqttClient() {
        try {
            String clientid = IdUtils.fastSimpleUUID();
            // MQTT的连接设置
            MqttConnectOptions options = new MqttConnectOptions();
            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            // 设置连接的用户名
            options.setUserName(username);
            // 设置连接的密码
            options.setPassword(password.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //是否自动重连
            options.setAutomaticReconnect(true);
            /*
            //同步阻塞式客户端
            // host为主机名,test为clientid即连接MQTT的客户端ID,一般以客户端唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
            client = new MqttClient(host, clientid, new MemoryPersistence());
            // 设置回调函数
            client.setCallback(new MqttPushClienCallback());
            client.connect(options);
            //订阅消息
            if (topic.contains(";")) {
                client.subscribe(topic.split(";"));
            } else {
                client.subscribe(topic);
            }*/

            //异步非阻塞式客户端
            mqttAsyncClient = new MqttAsyncClient(host, clientid, new MemoryPersistence());
            mqttAsyncClient.setCallback(new MqttPushClienCallback());
            mqttAsyncClient.connect(options);
            if (topic.contains(";")) {
                String[] split = topic.split(";");
                int[] qos = new int[split.length];
                for (int i = 0; i < qos.length; ++i) {
                    qos[i] = 1;
                }
                mqttAsyncClient.subscribe(split, qos);
            } else {
                mqttAsyncClient.subscribe(topic, 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 订阅主题
     *
     * @param topic 主题
     */
    public void subTopic(String topic) throws MqttException {
        subTopic(topic, 1);
    }

    /**
     * 订阅主题
     */
    public void subTopic(String topic, int qos) throws MqttException {
        client.subscribe(topic, qos);
    }

}
  • 连接信息在配置文件

  • 信息接收,异常重新类
package com.ha.mqtt.config.mqtt;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MqttPushClienCallback implements MqttCallback {

    private static Logger logger = LoggerFactory.getLogger(MqttPushClienCallback.class);

    @Autowired
    private MqttClientConfig mqttClientConfig;

    @Override
    public void connectionLost(Throwable throwable) {
        try {
            logger.info("MQTT连接断开,发起重连......");
            logger.info("............正在连接............");
            mqttClientConfig.initMqttClient();
            //心跳主题
            mqttClientConfig.subTopic("mqtt/face/heartbeat");
            //其他主题
            mqttClientConfig.subTopic("mqtt/face/by_ing112233/Rec");
            mqttClientConfig.subTopic("mqtt/face/by_ing112233/Snap");
            mqttClientConfig.subTopic("mqtt/face/by_ing112233/Ack");
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 接收mqttf服务信息
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        System.out.println(".......接收到mqtt信息.......");
        logger.info("topid:{}", topic);
        logger.info("mqttMessage:{}", mqttMessage.getPayload());
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }
}
  • 结果输出信息

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值