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

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

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

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

需要在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包不能省,在复制一下

        <!--mqtt依赖 start-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-integration</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-stream</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-mqtt</artifactId>
        </dependency>
        <!--mqtt依赖 end-->

二、连接管理(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<String, MqttClientConnect> 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<ContextRefreshedEvent> {

    @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<MqttServerEntity> 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> T getBean(String name) {
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(Class<T> 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;
    }


}

结束!!!

m2mqtt.net 是一个开源的 MQTT 客户端库,可以用于在 .NET 平台上创建 MQTT 客户端。要创建多个客户端,可以使用 m2mqtt.net 提供的 MqttClient 实例来实现。 首先,我们需要在代码中引入 MqttClient 的命名空间: ``` using uPLibrary.Networking.M2Mqtt; using uPLibrary.Networking.M2Mqtt.Messages; ``` 接着,我们可以创建多个 MqttClient 实例,每个实例都代表一个 MQTT 客户端。例如,下面的代码创建了两个客户端: ``` // 创建客户端1 MqttClient client1 = new MqttClient("broker.hivemq.com"); // 创建客户端2 MqttClient client2 = new MqttClient("iot.eclipse.org"); ``` 接下来,我们可以给每个客户端设置回调函数,用于接收订阅主题的消息: ``` // 为客户端1设置回调函数 client1.MqttMsgPublishReceived += Client1_MqttMsgPublishReceived; // 为客户端2设置回调函数 client2.MqttMsgPublishReceived += Client2_MqttMsgPublishReceived; ``` 最后,我们可以连接每个客户端并订阅感兴趣的主题: ``` // 连接客户端1并订阅主题 client1.Connect("client1"); client1.Subscribe(new string[] { "topic1" }, new byte[] { 0 }); // 连接客户端2并订阅主题 client2.Connect("client2"); client2.Subscribe(new string[] { "topic2" }, new byte[] { 0 }); ``` 以上代码演示了如何创建多个 MQTT 客户端并订阅不同的主题。在实际应用中,我们可以根据需要创建更多的客户端,并为每个客户端设置不同的回调函数和订阅主题,以满足不同场景的需求。
评论 23
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值