Преглед изворни кода

优化尖峰时段违规启动设备详情为批量查询 MongoDB,同时减少不必要的字段返回

lingpeng.li пре 5 месеци
родитељ
комит
892783defc

+ 176 - 210
zgztBus/jeecg-module-lesm/src/main/java/org/jeecg/modules/homePageData/service/impl/HomePageDataServiceImpl.java

@@ -403,220 +403,212 @@ public class HomePageDataServiceImpl implements IHomePageDataService {
 
     @Override
     public List<IllegalResult> topsIllegalActivation() {
-
         List<IllegalResult> illegalResultList = new ArrayList<>();
+
+        // 查询尖峰相关的 LeanEventsHost
         LambdaQueryWrapper<LeanEventsHost> lambdaQueryWrapper = new LambdaQueryWrapper<>();
         lambdaQueryWrapper.eq(LeanEventsHost::getDeviceInformationId, "tops");
         lambdaQueryWrapper.eq(LeanEventsHost::getDeviceInformationType, "fpg_close");
         LeanEventsHost one = leanEventsHostService.getOne(lambdaQueryWrapper);
-        if (null != one) {
-
-            if (oConvertUtils.isNotEmpty(one.getDeviceInformationList())) {
-
-                // 使用 String.split() 按逗号分割字符串
-                String[] array = one.getDeviceInformationList().split(",");
-
-                // 将数组转换为 List
-                List<String> list = Arrays.asList(array);
-
-                // 获取当天的日期和时间
-                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
-                String todayDateTime = LocalDateTime.now().format(formatter); // 获取当前的日期时间
-                String todayDate = todayDateTime.split(" ")[0]; // 获取当前日期部分(yyyy-MM-dd)
 
-
-                // 使用 deviceInformationId (s) 和 today's date 来构造 warnInfoLambdaQueryWrapper
-
-                LambdaQueryWrapper<LeanEventWarnInfo> warnInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
-                warnInfoLambdaQueryWrapper.in(LeanEventWarnInfo::getDeviceInformationId, list);
-                warnInfoLambdaQueryWrapper.likeRight(LeanEventWarnInfo::getCreateTime, todayDate);
-
-                // 查询结果
-                List<LeanEventWarnInfo> warnInfoList = leanEventWarnInfoService.list(warnInfoLambdaQueryWrapper);
-
-                // 使用 Map 去重,基于 deviceInformationId
-                Map<String, LeanEventWarnInfo> uniqueWarnInfoMap = warnInfoList.stream()
+        if (one != null && oConvertUtils.isNotEmpty(one.getDeviceInformationList())) {
+            // 分割设备信息列表
+            List<String> deviceInfoList = Arrays.asList(one.getDeviceInformationList().split(","));
+
+            // 获取当天日期
+            String todayDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
+
+            // 查询所有尖峰时段配置
+            List<PeaksAndValleysTimeConfig> timeConfigs = peaksAndValleysTimeConfigService.list(
+                    new LambdaQueryWrapper<PeaksAndValleysTimeConfig>().eq(PeaksAndValleysTimeConfig::getType, "tops")
+            );
+
+            // 查询告警信息
+            List<LeanEventWarnInfo> warnInfoList = leanEventWarnInfoService.list(
+                    new LambdaQueryWrapper<LeanEventWarnInfo>()
+                            .in(LeanEventWarnInfo::getDeviceInformationId, deviceInfoList)
+                            .likeRight(LeanEventWarnInfo::getCreateTime, todayDate)
+            );
+
+            // 根据 DeviceInformationId 去重
+            Map<String, LeanEventWarnInfo> uniqueWarnInfoMap = warnInfoList.stream()
+                    .collect(Collectors.toMap(
+                            LeanEventWarnInfo::getDeviceInformationId,
+                            warnInfo -> warnInfo,
+                            (existing, replacement) -> existing
+                    ));
+
+            List<LeanEventWarnInfo> distinctWarnInfoList = new ArrayList<>(uniqueWarnInfoMap.values());
+
+            // 构建设备 ID 列表
+            List<String> deviceInformationIds = distinctWarnInfoList.stream()
+                    .map(LeanEventWarnInfo::getDeviceInformationId)
+                    .collect(Collectors.toList());
+
+            for (PeaksAndValleysTimeConfig timeConfig : timeConfigs) {
+                // 设置查询时间范围
+                String startTimeStr = todayDate + " " + timeConfig.getStartTime();
+                String endTimeStr = todayDate + " " + timeConfig.getEndTime();
+
+                Query batchQuery = new Query();
+                batchQuery.addCriteria(Criteria.where("deviceInformationId").in(deviceInformationIds));
+                batchQuery.addCriteria(Criteria.where("datestr").gte(startTimeStr).lte(endTimeStr));
+                batchQuery.fields().include("deviceInformationId").include("datestr").include("ingTime").include("power");
+
+                // 批量查询 MongoDB 数据
+                List<LeanModelDeviceHistoryInfo> deviceHistoryInfos = mongoTemplate.find(
+                        batchQuery, LeanModelDeviceHistoryInfo.class, "leanmodel_run_realtime"
+                );
+
+                // 筛选时间范围内的数据
+                List<LeanModelDeviceHistoryInfo> filteredDeviceHistoryInfos = deviceHistoryInfos.stream()
+                        .filter(info -> containsCreateTime(
+                                DateUtils.str2Date(info.getDatestr(), DateUtils.datetimeFormat.get()).toInstant()
+                                        .atZone(ZoneId.systemDefault()).toLocalDateTime(), // 将 Instant 转为 LocalDateTime
+                                startTimeStr, endTimeStr
+                        ))
+                        .collect(Collectors.toList());
+
+
+                // 获取每个设备最新的记录
+                Map<String, LeanModelDeviceHistoryInfo> latestDataMap = filteredDeviceHistoryInfos.stream()
                         .collect(Collectors.toMap(
-                                LeanEventWarnInfo::getDeviceInformationId,  // 用 deviceInformationId 作为 key
-                                warnInfo -> warnInfo,  // value 为 warnInfo 对象
-                                (existing, replacement) -> existing)); // 如果有重复的 key,保留第一个
-
-                // 获取去重后的结果列表
-                List<LeanEventWarnInfo> distinctWarnInfoList = uniqueWarnInfoMap.values().stream().collect(Collectors.toList());
-
-                LambdaQueryWrapper<PeaksAndValleysTimeConfig> wrapper = new LambdaQueryWrapper<>();
-                wrapper.eq(PeaksAndValleysTimeConfig::getType, "tops");
-                List<PeaksAndValleysTimeConfig> peaksAndValleysTimeConfigs = peaksAndValleysTimeConfigService.list(wrapper);
-
-                for (PeaksAndValleysTimeConfig peaksAndValleysTimeConfig : peaksAndValleysTimeConfigs) {
-
-                    for (LeanEventWarnInfo leanEventWarnInfo : distinctWarnInfoList) {
-
-
-                        Query querylr = new Query();
-
-                        // 添加筛选条件:deviceRegionId 和 当月日期范围
-                        querylr.addCriteria(Criteria.where("deviceInformationId").in(leanEventWarnInfo.getDeviceInformationId()));
-
-                        // 执行查询,获取该区域的设备统计数据
-                        List<LeanModelDeviceHistoryInfo> deviceStatiscsModelMongodbList = mongoTemplate.find(
-                                querylr, LeanModelDeviceHistoryInfo.class, "leanmodel_run_realtime");
-
-                        List<LeanModelDeviceHistoryInfo> arrayList = new ArrayList<>();
-                        // 采集时间
-                        for (LeanModelDeviceHistoryInfo leanModelDeviceHistoryInfo : deviceStatiscsModelMongodbList) {
-
-                            Instant instant = DateUtils.str2Date(leanModelDeviceHistoryInfo.getDatestr(), DateUtils.datetimeFormat.get()).toInstant();
-                            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
-
-                            // 获取今天的日期
-                            LocalDate today = LocalDate.now();
-
-                            // 格式化为 yyyy-MM-dd 格式的字符串
-                            DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
-                            String dayDate = today.format(formatter1);
-
-                            if (containsCreateTime(localDateTime, dayDate + " " + peaksAndValleysTimeConfig.getStartTime(), dayDate + " " + peaksAndValleysTimeConfig.getEndTime())) {
-
-                                arrayList.add(leanModelDeviceHistoryInfo);
-
+                                LeanModelDeviceHistoryInfo::getDeviceInformationId,
+                                data -> data,
+                                (existing, replacement) -> {
+                                    String existingDateStr = existing.getDatestr();
+                                    String replacementDateStr = replacement.getDatestr();
+                                    return existingDateStr.compareTo(replacementDateStr) >= 0 ? existing : replacement;
+                                }
+                        ));
+
+                // 批量处理 IllegalResult
+                illegalResultList.addAll(latestDataMap.values().parallelStream()
+                        .map(info -> {
+                            IllegalResult result = new IllegalResult();
+                            DeviceInformation deviceInformation = deviceInformationService.getOne(
+                                    new LambdaQueryWrapper<DeviceInformation>().eq(DeviceInformation::getId, info.getDeviceInformationId())
+                            );
+                            if (deviceInformation != null) {
+                                result.setDeviceTitle(deviceInformation.getDeviceTitle());
                             }
-
-                        }
-
-                        List<LeanModelDeviceHistoryInfo> leanModelDeviceHistoryInfos = filterLatestData(arrayList);
-
-
-                        for (LeanModelDeviceHistoryInfo leanModelDeviceHistoryInfo : leanModelDeviceHistoryInfos) {
-                            IllegalResult illegalResult = new IllegalResult();
-
-                            LambdaQueryWrapper<DeviceInformation> queryWrapper = new LambdaQueryWrapper<>();
-                            queryWrapper.eq(DeviceInformation::getId,leanModelDeviceHistoryInfo.getDeviceInformationId());
-                            DeviceInformation deviceInformation = deviceInformationService.getOne(queryWrapper);
-                            if(null != deviceInformation) {
-                                illegalResult.setDeviceTitle(deviceInformation.getDeviceTitle());
-                            }
-                            illegalResult.setIngTime(leanModelDeviceHistoryInfo.getIngTime());
-                            illegalResult.setPower(leanModelDeviceHistoryInfo.getPower());
-                            illegalResult.setCreateTime(DateUtils.str2Date(leanModelDeviceHistoryInfo.getDatestr(), DateUtils.datetimeFormat.get()));
-
-                            illegalResultList.add(illegalResult);
-                        }
-                    }
-                }
+                            result.setIngTime(info.getIngTime());
+                            result.setPower(info.getPower());
+                            result.setCreateTime(DateUtils.str2Date(info.getDatestr(), DateUtils.datetimeFormat.get()));
+                            return result;
+                        })
+                        .collect(Collectors.toList()));
             }
         }
 
         return illegalResultList;
     }
 
+
     @Override
     public List<IllegalResult> peaksIllegalActivation() {
         List<IllegalResult> illegalResultList = new ArrayList<>();
+
+        // 查询尖峰相关的 LeanEventsHost
         LambdaQueryWrapper<LeanEventsHost> lambdaQueryWrapper = new LambdaQueryWrapper<>();
         lambdaQueryWrapper.eq(LeanEventsHost::getDeviceInformationId, "peaks");
         lambdaQueryWrapper.eq(LeanEventsHost::getDeviceInformationType, "fpg_close");
         LeanEventsHost one = leanEventsHostService.getOne(lambdaQueryWrapper);
-        if (null != one) {
-
-            if (oConvertUtils.isNotEmpty(one.getDeviceInformationList())) {
-
-                // 使用 String.split() 按逗号分割字符串
-                String[] array = one.getDeviceInformationList().split(",");
 
-                // 将数组转换为 List
-                List<String> list = Arrays.asList(array);
-
-                // 获取当天的日期和时间
-                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
-                String todayDateTime = LocalDateTime.now().format(formatter); // 获取当前的日期时间
-                String todayDate = todayDateTime.split(" ")[0]; // 获取当前日期部分(yyyy-MM-dd)
-
-                // 使用 deviceInformationId (s) 和 today's date 来构造 warnInfoLambdaQueryWrapper
-
-                LambdaQueryWrapper<LeanEventWarnInfo> warnInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
-                warnInfoLambdaQueryWrapper.in(LeanEventWarnInfo::getDeviceInformationId, list);
-                warnInfoLambdaQueryWrapper.likeRight(LeanEventWarnInfo::getCreateTime, todayDate);
-
-                // 查询结果
-                List<LeanEventWarnInfo> warnInfoList = leanEventWarnInfoService.list(warnInfoLambdaQueryWrapper);
-
-                // 使用 Map 去重,基于 deviceInformationId
-                Map<String, LeanEventWarnInfo> uniqueWarnInfoMap = warnInfoList.stream()
+        if (one != null && oConvertUtils.isNotEmpty(one.getDeviceInformationList())) {
+            // 分割设备信息列表
+            List<String> deviceInfoList = Arrays.asList(one.getDeviceInformationList().split(","));
+
+            // 获取当天日期
+            String todayDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
+
+            // 查询所有尖峰时段配置
+            List<PeaksAndValleysTimeConfig> timeConfigs = peaksAndValleysTimeConfigService.list(
+                    new LambdaQueryWrapper<PeaksAndValleysTimeConfig>().eq(PeaksAndValleysTimeConfig::getType, "peaks")
+            );
+
+            // 查询告警信息
+            List<LeanEventWarnInfo> warnInfoList = leanEventWarnInfoService.list(
+                    new LambdaQueryWrapper<LeanEventWarnInfo>()
+                            .in(LeanEventWarnInfo::getDeviceInformationId, deviceInfoList)
+                            .likeRight(LeanEventWarnInfo::getCreateTime, todayDate)
+            );
+
+            // 根据 DeviceInformationId 去重
+            Map<String, LeanEventWarnInfo> uniqueWarnInfoMap = warnInfoList.stream()
+                    .collect(Collectors.toMap(
+                            LeanEventWarnInfo::getDeviceInformationId,
+                            warnInfo -> warnInfo,
+                            (existing, replacement) -> existing
+                    ));
+
+            List<LeanEventWarnInfo> distinctWarnInfoList = new ArrayList<>(uniqueWarnInfoMap.values());
+
+            // 构建设备 ID 列表
+            List<String> deviceInformationIds = distinctWarnInfoList.stream()
+                    .map(LeanEventWarnInfo::getDeviceInformationId)
+                    .collect(Collectors.toList());
+
+            for (PeaksAndValleysTimeConfig timeConfig : timeConfigs) {
+                // 设置查询时间范围
+                String startTimeStr = todayDate + " " + timeConfig.getStartTime();
+                String endTimeStr = todayDate + " " + timeConfig.getEndTime();
+
+                Query batchQuery = new Query();
+                batchQuery.addCriteria(Criteria.where("deviceInformationId").in(deviceInformationIds));
+                batchQuery.addCriteria(Criteria.where("datestr").gte(startTimeStr).lte(endTimeStr));
+                batchQuery.fields().include("deviceInformationId").include("datestr").include("ingTime").include("power");
+
+                // 批量查询 MongoDB 数据
+                List<LeanModelDeviceHistoryInfo> deviceHistoryInfos = mongoTemplate.find(
+                        batchQuery, LeanModelDeviceHistoryInfo.class, "leanmodel_run_realtime"
+                );
+
+                // 筛选时间范围内的数据
+                List<LeanModelDeviceHistoryInfo> filteredDeviceHistoryInfos = deviceHistoryInfos.stream()
+                        .filter(info -> containsCreateTime(
+                                DateUtils.str2Date(info.getDatestr(), DateUtils.datetimeFormat.get()).toInstant()
+                                        .atZone(ZoneId.systemDefault()).toLocalDateTime(), // 将 Instant 转为 LocalDateTime
+                                startTimeStr, endTimeStr
+                        ))
+                        .collect(Collectors.toList());
+
+
+                // 获取每个设备最新的记录
+                Map<String, LeanModelDeviceHistoryInfo> latestDataMap = filteredDeviceHistoryInfos.stream()
                         .collect(Collectors.toMap(
-                                LeanEventWarnInfo::getDeviceInformationId,  // 用 deviceInformationId 作为 key
-                                warnInfo -> warnInfo,  // value 为 warnInfo 对象
-                                (existing, replacement) -> existing)); // 如果有重复的 key,保留第一个
-
-                // 获取去重后的结果列表
-                List<LeanEventWarnInfo> distinctWarnInfoList = uniqueWarnInfoMap.values().stream().collect(Collectors.toList());
-
-                LambdaQueryWrapper<PeaksAndValleysTimeConfig> wrapper = new LambdaQueryWrapper<>();
-                wrapper.eq(PeaksAndValleysTimeConfig::getType, "peaks");
-                List<PeaksAndValleysTimeConfig> peaksAndValleysTimeConfigs = peaksAndValleysTimeConfigService.list(wrapper);
-
-                for (PeaksAndValleysTimeConfig peaksAndValleysTimeConfig : peaksAndValleysTimeConfigs) {
-
-                    for (LeanEventWarnInfo leanEventWarnInfo : distinctWarnInfoList) {
-
-
-                        Query querylr = new Query();
-
-                        // 添加筛选条件:deviceRegionId 和 当月日期范围
-                        querylr.addCriteria(Criteria.where("deviceInformationId").in(leanEventWarnInfo.getDeviceInformationId()));
-
-                        // 执行查询,获取该区域的设备统计数据
-                        List<LeanModelDeviceHistoryInfo> deviceStatiscsModelMongodbList = mongoTemplate.find(
-                                querylr, LeanModelDeviceHistoryInfo.class, "leanmodel_run_realtime");
-
-                        List<LeanModelDeviceHistoryInfo> arrayList = new ArrayList<>();
-                        // 采集时间
-                        for (LeanModelDeviceHistoryInfo leanModelDeviceHistoryInfo : deviceStatiscsModelMongodbList) {
-
-                            Instant instant = DateUtils.str2Date(leanModelDeviceHistoryInfo.getDatestr(), DateUtils.datetimeFormat.get()).toInstant();
-                            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
-
-                            // 获取今天的日期
-                            LocalDate today = LocalDate.now();
-
-                            // 格式化为 yyyy-MM-dd 格式的字符串
-                            DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
-                            String dayDate = today.format(formatter1);
-
-                            if (containsCreateTime(localDateTime, dayDate + " " + peaksAndValleysTimeConfig.getStartTime(), dayDate + " " + peaksAndValleysTimeConfig.getEndTime())) {
-
-                                arrayList.add(leanModelDeviceHistoryInfo);
-
+                                LeanModelDeviceHistoryInfo::getDeviceInformationId,
+                                data -> data,
+                                (existing, replacement) -> {
+                                    String existingDateStr = existing.getDatestr();
+                                    String replacementDateStr = replacement.getDatestr();
+                                    return existingDateStr.compareTo(replacementDateStr) >= 0 ? existing : replacement;
+                                }
+                        ));
+
+                // 批量处理 IllegalResult
+                illegalResultList.addAll(latestDataMap.values().parallelStream()
+                        .map(info -> {
+                            IllegalResult result = new IllegalResult();
+                            DeviceInformation deviceInformation = deviceInformationService.getOne(
+                                    new LambdaQueryWrapper<DeviceInformation>().eq(DeviceInformation::getId, info.getDeviceInformationId())
+                            );
+                            if (deviceInformation != null) {
+                                result.setDeviceTitle(deviceInformation.getDeviceTitle());
                             }
-
-                        }
-
-                        List<LeanModelDeviceHistoryInfo> leanModelDeviceHistoryInfos = filterLatestData(arrayList);
-
-
-                        for (LeanModelDeviceHistoryInfo leanModelDeviceHistoryInfo : leanModelDeviceHistoryInfos) {
-                            IllegalResult illegalResult = new IllegalResult();
-
-                            LambdaQueryWrapper<DeviceInformation> queryWrapper = new LambdaQueryWrapper<>();
-                            queryWrapper.eq(DeviceInformation::getId,leanModelDeviceHistoryInfo.getDeviceInformationId());
-                            DeviceInformation deviceInformation = deviceInformationService.getOne(queryWrapper);
-                            if(null != deviceInformation) {
-                                illegalResult.setDeviceTitle(deviceInformation.getDeviceTitle());
-                            }
-                            illegalResult.setIngTime(leanModelDeviceHistoryInfo.getIngTime());
-                            illegalResult.setPower(leanModelDeviceHistoryInfo.getPower());
-                            illegalResult.setCreateTime(DateUtils.str2Date(leanModelDeviceHistoryInfo.getDatestr(), DateUtils.datetimeFormat.get()));
-
-                            illegalResultList.add(illegalResult);
-                        }
-                    }
-                }
+                            result.setIngTime(info.getIngTime());
+                            result.setPower(info.getPower());
+                            result.setCreateTime(DateUtils.str2Date(info.getDatestr(), DateUtils.datetimeFormat.get()));
+                            return result;
+                        })
+                        .collect(Collectors.toList()));
             }
         }
 
         return illegalResultList;
     }
 
+
     @Override
     public List<String> latestMsg() {
 
@@ -726,32 +718,6 @@ public class HomePageDataServiceImpl implements IHomePageDataService {
     }
 
 
-    public List<LeanModelDeviceHistoryInfo> filterLatestData(List<LeanModelDeviceHistoryInfo> deviceStatiscsModelMongodbList) {
-        // 按照 deviceInformationId 分组,并找到每组中 datestr 最新的一条数据
-        Map<String, LeanModelDeviceHistoryInfo> latestDataMap = deviceStatiscsModelMongodbList.stream()
-                .collect(Collectors.toMap(
-                        LeanModelDeviceHistoryInfo::getDeviceInformationId,  // 根据 deviceInformationId 进行分组
-                        data -> data,  // 数据本身
-                        (existing, replacement) -> {
-                            // 按照 datestr(时间)比较取最新的
-                            String existingDateStr = existing.getDatestr();
-                            String replacementDateStr = replacement.getDatestr();
-                            try {
-                                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-                                Date existingDate = formatter.parse(existingDateStr);
-                                Date replacementDate = formatter.parse(replacementDateStr);
-                                return existingDate.after(replacementDate) ? existing : replacement;
-                            } catch (Exception e) {
-                                return existing;  // 如果日期解析失败,默认返回现有的
-                            }
-                        }
-                ));
-
-        // 获取去重后的列表(即每个 deviceInformationId 对应最新的一条数据)
-        return new ArrayList<>(latestDataMap.values());
-    }
-
-
     // 提取公共逻辑到一个方法中
     private void processDeviceInformation(String deviceInformationId, String deviceInformationType, Map<String, Integer> res) {
         LambdaQueryWrapper<LeanEventsHost> lambdaQueryWrapper = new LambdaQueryWrapper<>();