iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Springboot整合mqtt服务的示例代码
  • 929
分享到

Springboot整合mqtt服务的示例代码

2024-04-02 19:04:59 929人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

首先在pom文件里引入MQtt的依赖配置 <!--mQtt--> <dependency> <g

首先在pom文件里引入MQtt的依赖配置

        <!--mQtt-->
        <dependency>
            <groupId>org.eclipse.paho</groupId>
            <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
            <version>1.2.4</version>
        </dependency>

其次在SpringBoot 的配置yml文件,配置mqtt的服务配置

spring:  
  mqtt:
    url: tcp://127.0.0.1:1883
    client-id: niubility-tiger
    username:
    passWord:
    topic: [/unify/test]

创建 MqttProperties配置参数类

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
 
@Data
@ConfigurationProperties("spring.mqtt")
public class MqttProperties {
    private String url;
    private String clientId;
    private String username;
    private String password;
    private String[] topic;
}

创建 MqttConfiguration 配置类

import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.tool.utils.Func;
import org.springblade.ubw.listener.MqttSubscribeListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
@EnableConfigurationProperties({MqttProperties.class})
public class MqttConfiguration {
    private static final Logger log = LoggerFactory.getLogger(MqttConfiguration.class);
    @Autowired
    private MqttProperties mqttProperties;
 
    public MqttConfiguration() {
    }
 
    @Bean
    public MqttConnectOptions mqttConnectOptions() {
        MqttConnectOptions connectOptions = new MqttConnectOptions();
        connectOptions.setServerURIs(new String[]{this.mqttProperties.getUrl()});
        if (Func.isNotBlank(this.mqttProperties.getUrl())) {
            connectOptions.setUserName(this.mqttProperties.getUsername());
        }
 
        if (Func.isNotBlank(this.mqttProperties.getPassword())) {
            connectOptions.setPassword(this.mqttProperties.getPassword().toCharArray());
        }
 
        connectOptions.seTKEepAliveInterval(60);
        return connectOptions;
    }
 
    @Bean
    public IMqttClient mqttClient(MqttConnectOptions options) throws MqttException {
        IMqttClient mqttClient = new MqttClient(this.mqttProperties.getUrl(), this.mqttProperties.getClientId());
        mqttClient.connect(options);
        for(int i = 0; i< this.mqttProperties.getTopic().length; ++i) {
            mqttClient.subscribe(this.mqttProperties.getTopic()[i], new MqttSubscribeListener());
        }
        return mqttClient;
    }
}

创建 订阅事件类

import org.springframework.context.ApplicationEvent;
 
 
public class UWBMqttSubscribeEvent extends ApplicationEvent {
    private String topic;
 
    public UWBMqttSubscribeEvent(String topic, Object source) {
        super(source);
        this.topic = topic;
    }
 
    public String getTopic() {
        return this.topic;
    }
}

创建订阅事件监听器

import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.ubw.event.UWBMqttSubscribeEvent;
 
 
public class MqttSubscribeListener implements IMqttMessageListener {
 
    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) {
        String content = new String(mqttMessage.getPayload());
        UWBMqttSubscribeEvent event = new UWBMqttSubscribeEvent(s, content);
        SpringUtil.publishEvent(event);
    }
}

创建mqtt消息事件异步处理监听器

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.tool.utils.Func;
import org.springblade.ubw.config.MqttProperties;
import org.springblade.ubw.event.UWBMqttSubscribeEvent;
import org.springblade.ubw.service.MqttService;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
 
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
 
 
@Configuration
public class MqttEventListener {
 
 
    private static final Logger log = LoggerFactory.getLogger(MqttEventListener.class);
 
    @Resource
    private MqttProperties mqttProperties;
 
    @Resource
    private MqttService mqttService;
 
    private String processTopic (String topic) {
        List<String> topics = Arrays.asList(mqttProperties.getTopic());
        for (String wild : topics) {
            wild = wild.replace(StringPool.HASH, StringPool.EMPTY);
            if (topic.startsWith(wild)) {
                return topic.replace(wild, StringPool.EMPTY);
            }
        }
        return StringPool.EMPTY;
    }
 
 
    @Async
    @EventListener(UWBMqttSubscribeEvent.class)
    public void listen (UWBMqttSubscribeEvent event) {
        String topic = processTopic(event.getTopic());
        Object source = event.getSource();
        if (Func.isEmpty(source)) {
            return;
        }
        mqttService.issue(topic,source);
//        log.info("mqtt接收到 通道 {} 的信息为:{}",topic,source);
    }
}

创建MqttService 数据处理服务类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.tool.utils.Func;
import org.springblade.ubw.area.entity.WorkArea;
import org.springblade.ubw.area.entity.WorkSite;
import org.springblade.ubw.area.entity.WorkSiteNeighbourInfo;
import org.springblade.ubw.area.entity.WorkSitePassInfo;
import org.springblade.ubw.area.service.WorkAreaService;
import org.springblade.ubw.area.service.WorkSiteNeighbourInfoService;
import org.springblade.ubw.area.service.WorkSitePassInfoService;
import org.springblade.ubw.area.service.WorkSiteService;
import org.springblade.ubw.constant.UbwConstant;
import org.springblade.ubw.history.entity.HistoryLocusInfo;
import org.springblade.ubw.history.entity.HistoryOverTimeSosAlarmInfo;
import org.springblade.ubw.history.service.HistoryLocusInfoService;
import org.springblade.ubw.history.service.HistoryOverTimeSosAlarmInfoService;
import org.springblade.ubw.loc.entity.LocStatusInfo;
import org.springblade.ubw.loc.entity.LocStatusInfoHistory;
import org.springblade.ubw.loc.service.LocStatusInfoHistoryService;
import org.springblade.ubw.loc.service.LocStatusInfoService;
import org.springblade.ubw.msg.entity.*;
import org.springblade.ubw.msg.service.*;
import org.springblade.ubw.system.entity.*;
import org.springblade.ubw.system.service.*;
import org.springblade.ubw.system.wrapper.MqttWrapper;
import org.springframework.stereotype.Service;
 
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
 
 
@Service
public class MqttService {
 
    private static final Logger log = LoggerFactory.getLogger(MqttService.class);
 
    @Resource
    private EmployeeAndDepartmentService employeeAndDepartmentService;
 
    @Resource
    private VehicleInfoService vehicleInfoService;
 
    @Resource
    private WorkSiteService workSiteService;
 
    @Resource
    private LocStatusInfoService locStatusInfoService;
 
    @Resource
    private LocStatusInfoHistoryService locStatusInfoHistoryService;
 
    @Resource
    private LocOverTimeSosAlarminfoService locOverTimeSosAlarminfoService;
 
    @Resource
    private LocAreaOverSosAlarminfoService locAreaOverSosAlarmInfoService;
 
    @Resource
    private LocSosAlarminfoService locSosAlarminfoService;
 
    @Resource
    private AttendanceInfoService attendanceInfoService;
 
    @Resource
    private HistoryLocusInfoService historyLocusInfoService;
 
    @Resource
    private WorkSitePassInfoService workSitePassInfoService;
 
    @Resource
    private EnvironmentalMonitorInfoService environmentalMonitorInfoService;
 
    @Resource
    private TrAlertService trAlertService;
 
    @Resource
    private AddEvacuateInfoService addEvacuateInfoService;
 
    @Resource
    private CancelEvacuateInfoService cancelEvacuateInfoService;
 
    @Resource
    private WorkSiteNeighbourInfoService workSiteNeighbourInfoService;
 
    @Resource
    private LinkMsgAlarmInfoService linkMsgAlarmInfoService;
 
    @Resource
    private LeaderEmployeeInfoService leaderEmployeeInfoService;
 
    @Resource
    private ElectricMsgInfoService electricMsgInfoService;
 
    @Resource
    private WorkAreaService workAreaService;
 
    @Resource
    private HistoryOverTimeSosAlarmInfoService historyOverTimeSosAlarmInfoService;
 
    @Resource
    private SpecialWorksService specialWorksService;
 
    @Resource
    private AttendanceLocusInfoService attendanceLocusInfoService;
 
    @Resource
    private WorkTypeService workTypeService;
 
    @Resource
    private OfficePositionService officePositionService;
 
    @Resource
    private ClassTeamService classTeamService;
 
    
    public void issue(String topic,Object source){
        switch(topic){
            case UbwConstant.TOPIC_EMP :
                //人员和部门信息
                employeeAndDepartmentService.saveBatch(source);
                break;
            case UbwConstant.TOPIC_VEHICLE :
                //车辆信息
                List<VehicleInfo> vehicleInfos = MqttWrapper.build().toEntityList(source,new VehicleInfo());
                vehicleInfoService.deleteAll();
                vehicleInfoService.saveBatch(vehicleInfos);
                break;
            case UbwConstant.TOPIC_WORK_SITE :
                //基站信息
                List<WorkSite> workSites = MqttWrapper.build().toEntityList(source,new WorkSite());
                workSiteService.deleteAll();
                workSiteService.saveBatch(workSites);
                break;
            case UbwConstant.TOPIC_LOC_STATUS:
                //井下车辆人员实时
                List<LocStatusInfo> locStatusInfos = MqttWrapper.build().toEntityList(source,new LocStatusInfo());
                if (Func.isEmpty(locStatusInfos)){
                    break;
                }
                locStatusInfoService.deleteAll();
                //筛选入井人员列表
                List<LocStatusInfo> inWellList = locStatusInfos.stream().filter(s -> s.getIsInWell() == 1).collect(Collectors.toList());
                locStatusInfoService.saveBatch(inWellList);
                //人员历史数据入库
                List<LocStatusInfoHistory> locStatusInfoHistorys = MqttWrapper.build().toEntityList(source,new LocStatusInfoHistory());
                locStatusInfoHistoryService.saveBatch(locStatusInfoHistorys);
                break;
            case UbwConstant.TOPIC_LOC_OVER_TIME:
                //超时报警信息
                List<LocOverTimeSosAlarminfo> locOverTimeSosAlarmInfos = MqttWrapper.build().toEntityList(source,new LocOverTimeSosAlarminfo());
                locOverTimeSosAlarminfoService.saveBatch(locOverTimeSosAlarmInfos);
                break;
            case UbwConstant.TOPIC_LOC_OVER_AREA:
                //超员报警信息
                List<LocAreaOverSosAlarminfo> locAreaOverSosAlarmInfos = MqttWrapper.build().toEntityList(source,new LocAreaOverSosAlarminfo());
                locAreaOverSosAlarmInfoService.saveBatch(locAreaOverSosAlarmInfos);
                break;
            case UbwConstant.TOPIC_LOC_SOS:
                //求救报警信息
                List<LocSosAlarminfo> locSosAlarmInfos = MqttWrapper.build().toEntityList(source,new LocSosAlarminfo());
                locSosAlarminfoService.saveBatch(locSosAlarmInfos);
                break;
            case UbwConstant.TOPIC_ATTEND:
                //考勤信息
                List<AttendanceInfo> attendanceInfos = MqttWrapper.build().toEntityList(source,new AttendanceInfo());
                attendanceInfoService.saveBatch(attendanceInfos);
                break;
            case UbwConstant.TOPIC_HISTORY_LOCUS:
                //精确轨迹信息
                List<HistoryLocusInfo> historyLocusInfos = MqttWrapper.build().toEntityList(source,new HistoryLocusInfo());
                historyLocusInfoService.saveBatch(historyLocusInfos);
                break;
            case UbwConstant.TOPIC_WORK_SITE_PASS:
                //基站经过信息
                List<WorkSitePassInfo> workSitePassInfos = MqttWrapper.build().toEntityList(source,new WorkSitePassInfo());
                workSitePassInfoService.saveBatch(workSitePassInfos);
                break;
            case UbwConstant.TOPIC_ENV_MON:
                //环境监测信息
                List<EnvironmentalMonitorInfo> environmentalMonitorInfos = MqttWrapper.build().toEntityList(source,new EnvironmentalMonitorInfo());
                environmentalMonitorInfoService.saveBatch(environmentalMonitorInfos);
                break;
            case UbwConstant.TOPIC_TR_ALERT:
                //环境监测报警信息
                List<TrAlert> trAlerts = MqttWrapper.build().toEntityList(source,new TrAlert());
                trAlertService.saveBatch(trAlerts);
                break;
            case UbwConstant.TOPIC_ADD_EVA:
                //下发撤离信息
                List<AddEvacuateInfo> addEvacuateInfos = MqttWrapper.build().toEntityList(source,new AddEvacuateInfo());
                addEvacuateInfoService.saveBatch(addEvacuateInfos);
                break;
            case UbwConstant.TOPIC_CANCEL_EVA:
                //取消撤离信息
                List<CancelEvacuateInfo> cancelEvacuateInfos = MqttWrapper.build().toEntityList(source,new CancelEvacuateInfo());
                cancelEvacuateInfoService.saveBatch(cancelEvacuateInfos);
                break;
            case UbwConstant.TOPIC_WORK_SITE_NEI:
                //相邻基站关系信息
                workSiteNeighbourInfoService.deleteAll();
                List<WorkSiteNeighbourInfo> workSiteNeighbourInfos = MqttWrapper.build().toEntityList(source,new WorkSiteNeighbourInfo());
                workSiteNeighbourInfoService.saveBatch(workSiteNeighbourInfos);
                break;
            case UbwConstant.TOPIC_LINK_MSG:
                //基站链路信息
                linkMsgAlarmInfoService.deleteAll();
                List<LinkMsgAlarmInfo> linkMsgAlarmInfos = MqttWrapper.build().toEntityList(source,new LinkMsgAlarmInfo());
                linkMsgAlarmInfoService.saveBatch(linkMsgAlarmInfos);
                break;
            case UbwConstant.TOPIC_LEADER_EMP:
                //带班领导信息
                leaderEmployeeInfoService.deleteAll();
                List<LeaderEmployeeInfo> leaderEmployeeInfos = MqttWrapper.build().toEntityList(source,new LeaderEmployeeInfo());
                leaderEmployeeInfoService.saveBatch(leaderEmployeeInfos);
                break;
            case UbwConstant.TOPIC_ELE_MSG:
                //低电报警信息
                List<ElectricMsgInfo> electricMsgInfos = MqttWrapper.build().toEntityList(source,new ElectricMsgInfo());
                electricMsgInfoService.saveBatch(electricMsgInfos);
                break;
            case UbwConstant.TOPIC_WORK_AREA:
                //区域信息
                workAreaService.deleteAll();
                List<WorkArea> workAreas = MqttWrapper.build().toEntityList(source,new WorkArea());
                workAreaService.saveBatch(workAreas);
                break;
            case UbwConstant.TOPIC_HIS_OVER_TIME_SOS:
                //历史超时报警信息
                List<HistoryOverTimeSosAlarmInfo> historyOverTimeSosAlarmInfos = MqttWrapper.build().toEntityList(source,new HistoryOverTimeSosAlarmInfo());
                historyOverTimeSosAlarmInfoService.saveBatch(historyOverTimeSosAlarmInfos);
                break;
            case UbwConstant.TOPIC_SPECIAL_WORK:
                //特种人员预设线路信息
                specialWorksService.deleteAll();
                List<SpecialWorks> specialWorks = MqttWrapper.build().toEntityList(source,new SpecialWorks());
                specialWorksService.saveBatch(specialWorks);
                break;
            case UbwConstant.TOPIC_ATTEND_LOC:
                //历史考勤轨迹信息
                List<AttendanceLocusInfo> attendanceLocusInfos = MqttWrapper.build().toEntityList(source,new AttendanceLocusInfo());
                attendanceLocusInfoService.saveBatch(attendanceLocusInfos);
                break;
            case UbwConstant.TOPIC_WORK_TYPE:
                //工种信息
                workTypeService.deleteAll();
                List<WorkType> workTypes = MqttWrapper.build().toEntityList(source,new WorkType());
                workTypeService.saveBatch(workTypes);
                break;
            case UbwConstant.TOPIC_OFFICE_POS:
                //职务信息
                officePositionService.deleteAll();
                List<OfficePosition> officePositions = MqttWrapper.build().toEntityList(source,new OfficePosition());
                officePositionService.saveBatch(officePositions);
                break;
            case UbwConstant.TOPIC_CLASS_TEAM:
                //班组信息
                classTeamService.deleteAll();
                List<ClassTeam> classTeams = MqttWrapper.build().toEntityList(source,new ClassTeam());
                classTeamService.saveBatch(classTeams);
                break;
            default : //可选
                break;
        }
    }
}

完结,小伙伴们,可以根据这个demo 改造自己的mqtt服务处理!!!

以上就是Springboot整合mqtt服务的示例代码的详细内容,更多关于Springboot整合mqtt的资料请关注编程网其它相关文章!

--结束END--

本文标题: Springboot整合mqtt服务的示例代码

本文链接: https://www.lsjlt.com/news/143059.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Springboot整合mqtt服务的示例代码
    首先在pom文件里引入mqtt的依赖配置 <!--mqtt--> <dependency> <g...
    99+
    2024-04-02
  • SpringBoot整合aws的示例代码
    业务需求 将本地的一些文件保存到aws上 引入依赖 创建client 工具类 引入依赖 <dependency> ...
    99+
    2024-04-02
  • SpringBoot整合Liquibase的示例代码
    目录整合1整合2SpringBoot整合Liquibase虽然不难但坑还是有一点的,主要集中在配置路径相关的地方,在此记录一下整合的步骤,方便以后自己再做整合时少走弯路,当然也希望能...
    99+
    2024-04-02
  • SpringBoot整合ElasticSearch的示例代码
    ElasticSearch作为基于Lucene的搜索服务器,既可以作为一个独立的服务部署,也可以签入Web应用中。SpringBoot作为Spring家族的全新框架,使得使用SpringBoot开发Spring应用变得非常简单。本文要介绍如...
    99+
    2023-05-31
    spring boot elasticsearch
  • SpringBoot整合SpringDataRedis的示例代码
      本文介绍下SpringBoot如何整合SpringDataRedis框架的,SpringDataRedis具体的内容在前面已经介绍过了,可自行参考。 1....
    99+
    2024-04-02
  • SpringBoot整合logback的示例代码
    Logback简介 1、logback和log4j是同一个作者,logback可以看作是log4j的升级版 2、logback分为三个模块, logback-core, logbac...
    99+
    2024-04-02
  • SpringBoot整合ShardingSphere的示例代码
    目录一、相关依赖二、Nacos数据源配置三、项目配置四、验证概要: ShardingSphere是一套开源的分布式数据库中间件解决方案组成的生态圈,它由Sharding-JDBC、S...
    99+
    2024-04-02
  • Springboot整合kafka的示例代码
    目录1.整合kafka2.消息发送2.1发送类型2.2序列化2.3分区策略3.消息消费3.1消息组别3.2位移提交1. 整合kafka 1、引入依赖 <dependency&...
    99+
    2024-04-02
  • SpringBoot整合jersey的示例代码
    这篇文章主要从以下几个方面来介绍。简单介绍下jersey,springboot,重点介绍如何整合springboot与jersey。 什么是jersey 什么是springboot 为什么要使用springboot+jersey 如...
    99+
    2023-05-31
    springboot jersey ers
  • springboot 整合sentinel的示例代码
    目录1. 安装sentinel2.客户端连接1. 安装sentinel         下载地址:https://github.com/ali...
    99+
    2024-04-02
  • SpringBoot整合JdbcTemplate的示例代码
    目录前言初始化SpringBoot项目使用IDEA创建项目导入JDBC依赖导入数据库驱动修改配置文件数据库sys_user表结构测试类代码查询sys_user表数据量查询sys_us...
    99+
    2024-04-02
  • springboot 整合hbase的示例代码
    目录前言HBase 定义HBase 数据模型物理存储结构数据模型1、Name Space2、Region3、Row4、Column5、Time Stamp6、Cell搭建步骤1、官网...
    99+
    2024-04-02
  • SpringBoot整合Minio的示例代码
    SpringBoot整合Minio 进入Minio官网,下载对应的Minio版本 官网安装文档 下载完成之后,启动(windows版) minio.exe server D:\m...
    99+
    2022-12-27
    SpringBoot整合Minio SpringBoot Minio整合 SpringBoot Minio
  • springboot整合xxl-job的示例代码
    目录关于xxl-job调度中心执行器关于xxl-job 在我看来,总体可以分为三大块: 调度中心执行器配置定时任务 调度中心 简单来讲就是 xxl-job-admin那个模块,配置:...
    99+
    2024-04-02
  • SpringBoot整合MyBatis-Plus的示例代码
    目录前言源码环境开发工具 SQL脚本 正文单工程POM文件(注意) application.properties(注意)自定义配置(注意)实体类(注意)...
    99+
    2024-04-02
  • springboot整合mongodb changestream的示例代码
    目录前言Change Stream 介绍环境准备Java客户端操作changestream1、引入maven依赖2、测试类核心代码下面来看看具体的整合步骤1、引入核心依赖2、核心配置...
    99+
    2024-04-02
  • SpringBoot整合Shiro和Redis的示例代码
    目录1.准备工作2.编写index,login,register三个JSP3.实现User、Role、Permission三个POJO4.实现Controller、Service、D...
    99+
    2024-04-02
  • SpringBoot整合Redis管道的示例代码
    目录1. Redis 之管道(pipeline)2. SpringBoot 整合 Redis 管道实例1. Redis 之管道(pipeline) 执行一个Redis命令,Redis...
    99+
    2024-04-02
  • SpringBoot框架整合SwaggerUI的示例代码
    整合swagger进行模块测试 注意事项:为方便SpringBoot更好的整合Swagger,需要专门放置在一个模块中(maven子工程) 创建公共模块,整合swagger,为了所有...
    99+
    2024-04-02
  • SpringBoot示例代码整合Redis详解
    目录Redis 简介Redis 优势Redis与其他key-value存储有什么不同添加Redis依赖包配置Redis数据库连接编写Redis操作工具类测试Redis 简介 Redi...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作