SpringBoot 整合MQTT客户端连接多个服务端(多个emqx)

在本篇内容描述之前,先回顾下上一篇内容 :

SpringBoot 整合MQTT发布和订阅消息处理
上一篇内容讲述了单个mqtt客户端连接一个指定的mqtt服务器,一般来说是够用的,但最近一个项目需求是要接收多个mqtt服务器的数据,如果还按上一篇文章的处理方法,就只能讲代码类复制多个这样实现,但这样做的后果就是代码不美观不便于维护,于是就整理了这篇文章,springboot用同一套代码实现多个mqtt服务器的连接和管理:

大致结构,三个类文件即可实现

SpringBoot 整合MQTT客户端连接多个服务端(多个emqx)_第1张图片

需要在mysql创建表(表结构如下):

CREATE TABLE `tbl_mqtt_server_dat` (
  `id` varchar(32) NOT NULL COMMENT '唯一标识',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
  `create_user` varchar(32) NOT NULL DEFAULT 'system' COMMENT '创建用户',
  `update_user` varchar(32) NOT NULL DEFAULT 'system' COMMENT '修改用户',
  `is_deleted` tinyint(1) NOT NULL DEFAULT '0' COMMENT '逻辑删除 1(true)已删除, 0(false)未删除',
  `server_host` varchar(32) NOT NULL COMMENT '服务器ip',
  `server_port` varchar(32) NOT NULL COMMENT '端口',
  `username` varchar(32) NOT NULL COMMENT '用户名',
  `password` varchar(32) NOT NULL COMMENT '密码',
  `client_id` varchar(32) NOT NULL COMMENT '客户端id',
  `client_topic` varchar(255) NOT NULL COMMENT '客户端订阅的主题(以'',''隔开)',
  `client_clean_session` tinyint(1) NOT NULL DEFAULT '0' COMMENT '客户端每次重连是否清除session, 0:否 1:是',
  `remark` varchar(255) NOT NULL COMMENT '备注',
  PRIMARY KEY (`id`) USING BTREE,
  KEY `is_deleted_index` (`is_deleted`) USING BTREE COMMENT '是否删除'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='MQTT服务器';

一、jar包不能省,在复制一下

        
        
            org.springframework.boot
            spring-boot-starter-integration
        
        
            org.springframework.integration
            spring-integration-stream
        
        
            org.springframework.integration
            spring-integration-mqtt
        
        

二、连接管理(MqttClientConnect)

import com.whcloud.wmp.datareciver.mqtt.callback.MqttClientCallback;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Component;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class MqttClientConnect {

    private MqttClient mqttClient;

    /**
     * 系统的mqtt客户端id
     */
    private String mqttClientId;

    /**
     * 客户端
     */
    public static ConcurrentHashMap mqttClients = new ConcurrentHashMap();

    /**
     * 客户端connect连接mqtt服务器
     *
     * @param userName     用户名
     * @param passWord     密码
     * @param mqttCallback 回调函数
     **/
    public void setMqttClient(String host, String clientId, String userName, String passWord, boolean cleanSession,  MqttCallback mqttCallback) throws MqttException {
        MqttConnectOptions options = mqttConnectOptions(host, clientId, userName, passWord, cleanSession);
        if (mqttCallback == null) {
            mqttClient.setCallback(new MqttClientCallback(mqttClientId));
        } else {
            mqttClient.setCallback(mqttCallback);
        }
        mqttClient.connect(options);
    }

    /**
     * MQTT连接参数设置
     */
    private MqttConnectOptions mqttConnectOptions(String host, String clientId, String userName, String passWord, boolean cleanSession) throws MqttException {
        mqttClient = new MqttClient(host, clientId, new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(userName);
        options.setPassword(passWord.toCharArray());
        options.setConnectionTimeout(30);///默认:30
        options.setAutomaticReconnect(true);//默认:false
        options.setCleanSession(cleanSession);//默认:true
        //options.setKeepAliveInterval(20);//默认:60
        return options;
    }

    /**
     * 关闭MQTT连接
     */
    public void close() throws MqttException {
        mqttClient.close();
        mqttClient.disconnect();
    }

    /**
     * 向某个主题发布消息 默认qos:1
     *
     * @param topic:发布的主题
     * @param msg:发布的消息
     */
    public void pub(String topic, String msg) throws MqttException {
        MqttMessage mqttMessage = new MqttMessage();
        //mqttMessage.setQos(2);
        mqttMessage.setPayload(msg.getBytes());
        MqttTopic mqttTopic = mqttClient.getTopic(topic);
        MqttDeliveryToken token = mqttTopic.publish(mqttMessage);
        token.waitForCompletion();
    }

    /**
     * 向某个主题发布消息
     *
     * @param topic: 发布的主题
     * @param msg:   发布的消息
     * @param qos:   消息质量    Qos:0、1、2
     */
    public void pub(String topic, String msg, int qos) throws MqttException {
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setQos(qos);
        mqttMessage.setPayload(msg.getBytes());
        MqttTopic mqttTopic = mqttClient.getTopic(topic);
        MqttDeliveryToken token = mqttTopic.publish(mqttMessage);
        token.waitForCompletion();
    }

    /**
     * 订阅多个主题 ,此方法默认的的Qos等级为:1
     *
     * @param topic 主题
     */
    public void sub(String[] topic) throws MqttException {
        mqttClient.subscribe(topic);
    }

    /**
     * 订阅某一个主题,可携带Qos
     *
     * @param topic 所要订阅的主题
     * @param qos   消息质量:0、1、2
     */
    public void sub(String topic, int qos) throws MqttException {
        mqttClient.subscribe(topic, qos);
    }

    public String getMqttClientId() {
        return mqttClientId;
    }

    public void setMqttClientId(String mqttClientId) {
        this.mqttClientId = mqttClientId;
    }

    //    /**
//     * main函数自己测试用
//     */
//    public static void main(String[] args) throws MqttException {
//        MqttClientConnect mqttClientConnect = new MqttClientConnect();
//        mqttClientConnect.setMqttClient("tcp://58.246.138.2:10883", "test-11111","admin", "public", new MqttClientCallback());
//        mqttClientConnect.pub("com/iot/init", "Mr.Qu" + (int) (Math.random() * 100000000));
//    }
}

三、回调函数类(处理数据,客户端异常等消息:MqttClientCallback)

import com.whcloud.wmp.configuration.core.context.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.amqp.core.AmqpTemplate;

/**
 * 常规MQTT回调函数
 *
 */
@Slf4j
public class MqttClientCallback implements MqttCallback {

    /**
     * 系统的mqtt客户端id
     */
    private String mqttClientId;

    public MqttClientCallback(String mqttClientId) {
        this.mqttClientId = mqttClientId;
    }

    private AmqpTemplate rabbitTemplate= SpringContextHolder.getBean(AmqpTemplate.class);

    /**
     * MQTT 断开连接会执行此方法
     */
    @Override
    public void connectionLost(Throwable throwable) {
        log.info("断开了MQTT连接 :{}", throwable.getMessage());
        //log.error(throwable.getMessage(), throwable);
    }

    /**
     * publish发布成功后会执行到这里
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.info("发布消息成功");
    }

    /**
     * subscribe订阅后得到的消息会执行到这里
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        //  TODO    此处可以将订阅得到的消息进行业务处理、数据存储
        //log.info("收到来自 "+ mqttClientId + "====" + topic + " 的消息:{}", new String(message.getPayload()));
        if("TEST".equals(topic)){
            //发送到rabbit消息队列
            rabbitTemplate.convertAndSend("environmentDirectExchange", "environmentNilometer", message.getPayload());
        }else {
            log.info("测试主题进入" + topic +"主题判断方法=================");
            //发送到rabbit消息队列
            rabbitTemplate.convertAndSend("environmentDirectExchange", "environmentMeteor", message.getPayload());
        }
    }
}

四、项目启动监听(创建所有和客户端连接)

import com.whcloud.wmp.datareciver.mqtt.callback.MqttClientCallback;
import com.whcloud.wmp.datareciver.mqtt.client.MqttClientConnect;
import com.whcloud.wmp.domain.entity.MqttServerEntity;
import com.whcloud.wmp.domain.service.MqttServerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 项目启动 监听主题
 *
 */
@Slf4j
@Component
public class MqttClientListener implements ApplicationListener {

    @Value("${spring.profiles.active}")
    private String active;

private volatile AtomicBoolean isInit=new AtomicBoolean(false);

    @Autowired
    private MqttServerService mqttServerService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            //防止重复触发
            if(!isInit.compareAndSet(false,true)) {
                return;
            }
            List mqttServerEntityList = mqttServerService.getMqttServerList();
            for (MqttServerEntity mqttServerDat:mqttServerEntityList) {
                MqttClientConnect mqttClientConnect = new MqttClientConnect();
                mqttClientConnect.setMqttClientId(mqttServerDat.getId());
                String host = "tcp://"+mqttServerDat.getServerHost()+":"+mqttServerDat.getServerPort();
                mqttClientConnect.setMqttClient(host, active.trim()+"-"+mqttServerDat.getClientId(), mqttServerDat.getUsername(), mqttServerDat.getPassword(), mqttServerDat.getClientCleanSession()==0?false:true, new MqttClientCallback(mqttServerDat.getId()));
                mqttClientConnect.sub(StringUtils.commaDelimitedListToStringArray(mqttServerDat.getClientTopic()));
                MqttClientConnect.mqttClients.put(mqttServerDat.getId(), mqttClientConnect);
                log.info("{}--连接成功!!订阅主题--{}", mqttServerDat.getId(), mqttServerDat.getClientTopic());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}

五、需要注意的是 MqttClientCallback 回调函数类中是不能用 @Autowired 注入的,这里提供一个解决办法  SpringContextHolder 类引入

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.
 *
 * @author
 */

public class SpringContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    /**
     * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        // NOSONAR
        SpringContextHolder.applicationContext = applicationContext;
    }

    /**
     * 取得存储在静态变量中的ApplicationContext.
     */
    public static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static  T getBean(String name) {
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static  T getBean(Class clazz) {
        checkApplicationContext();
        return (T) applicationContext.getBean(clazz);
    }

    /**
     * 清除applicationContext静态变量.
     */
    public static void cleanApplicationContext() {
        applicationContext = null;
    }

    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException(
                    "applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
        }
    }
}  
CoreConfiguration配置SpringContextHolder:

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
@EnableConfigurationProperties
public class CoreConfiguration {

    /**
     * Spring上下文工具配置
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(SpringContextHolder.class)
    public SpringContextHolder springContextHolder() {
        SpringContextHolder holder = new SpringContextHolder();
        log.info("SpringContextHolder >>>>>> [{}]", holder);
        return holder;
    }


}

结束!!!

你可能感兴趣的:(MQTT,mqtt服务器,多服务端,springboot,emqx,物联网)