Selaa lähdekoodia

增加API访问缓存,避免一直向IOT请求数据

wukai 1 vuosi sitten
vanhempi
commit
4316014e11

+ 19 - 132
ruoyi-admin/src/main/java/com/ruoyi/biz/controller/ApiController.java

@@ -1,11 +1,16 @@
 package com.ruoyi.biz.controller;
 
-import com.ruoyi.biz.domain.*;
+import com.ruoyi.biz.domain.IndexData;
+import com.ruoyi.biz.domain.TwinCalc2hr;
+import com.ruoyi.biz.domain.TwinDevice;
+import com.ruoyi.biz.domain.TwinRecordAlarms;
 import com.ruoyi.biz.service.*;
 import com.ruoyi.biz.service.impl.AsyncServiceImpl;
 import com.ruoyi.biz.tools.Tools;
+import com.ruoyi.common.constant.Constants;
 import com.ruoyi.common.core.controller.BaseController;
 import com.ruoyi.common.core.domain.R;
+import com.ruoyi.common.utils.CacheUtils;
 import com.ruoyi.common.utils.DateUtils;
 import com.ruoyi.common.utils.StringUtils;
 import com.ruoyi.system.service.ISysConfigService;
@@ -27,7 +32,6 @@ import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.math.BigDecimal;
-import java.math.RoundingMode;
 import java.net.URLEncoder;
 import java.text.ParseException;
 import java.time.LocalDate;
@@ -79,143 +83,26 @@ public class ApiController extends BaseController {
     @GetMapping("/index")
     @CrossOrigin(origins = "*")
     public R<IndexData> index() {
-        TwinCalc2hr calc2hr = calc2hrService.calcToday();
-        IndexData indexData = new IndexData();
-        IndexEfficiency efficiency = new IndexEfficiency(calc2hr);
-        indexData.setEfficiency(efficiency);
-        /*
-         *获取前面6天的数据,加上当天数据
-         */
-        LocalDate localDate = LocalDate.now().minusDays(6);
-        Date date = Date.from(localDate.atStartOfDay(ZoneOffset.of("+8")).toInstant());
-        List<TwinCalcDay> list = twinCalcDayService.selectTwinCalcDayListByTime(date);
-        TwinCalcDay today = new TwinCalcDay();
-        today.convert(calc2hr);
-        list.add(today);
-        List<WeekData> weekDataList = new ArrayList<>();
-        list.forEach(day -> {
-            WeekData weekData = new WeekData();
-            weekData.convert(day);
-            weekDataList.add(weekData);
-
-        });
-        indexData.setWeekData(weekDataList);
-        return R.ok(indexData);
+        Object d = CacheUtils.get(Constants.IOT_TOKEN, Constants.INDEX_CALC);
+        if (d != null) {
+            IndexData indexData = (IndexData) d;
+            return R.ok(indexData);
+        } else {
+            return R.fail();
+        }
     }
 
     @ApiOperation("首页告警数据")
     @GetMapping("/alarm")
     @CrossOrigin(origins = "*")
     public R<IndexData> alarm() {
-        IndexData indexData = new IndexData();
-        List<IndexAlarm> alarmList = new ArrayList<>();
-        List<IndexPan> panList = new ArrayList<>();
-        int stop1 = 0, stop2 = 0, stop6 = 0, stop8 = 0;
-        iotService.getToken();
-        List<TwinDevice> list = deviceService.selectTwinDeviceList(new TwinDevice());
-        Map<String, Long> panMap = new HashMap<>(16);
-        panHeadInfoService.selectTwinPanHeadInfoList(new TwinPanHeadInfo()).forEach(pan -> {
-            String key = pan.getDeviceId() + "_" + pan.getPhNum();
-            panMap.put(key, pan.getPhMax());
-        });
-        List<Future<Map<String, Object>>> futureList = new ArrayList<>();
-        for (int i = 0; i < list.size(); i++) {
-            TwinDevice twinDevice = list.get(i);
-            futureList.add(asyncService.currData(twinDevice));
-        }
-        try {
-            for (Future<Map<String, Object>> future : futureList) {
-                Map<String, Object> map = future.get();
-                TwinDevice device = (TwinDevice) map.get("device");
-                int total = (int) map.get("total");
-                if (total == 0) {
-                    //可能会出现接口返回无数据的情况
-                    continue;
-                }
-                int data4 = (int) map.get("Capacity_data_4");
-                if (data4 == 0) {
-                    //Capacity_data_4,如果设定落布米数为0,则证明当前数据无效
-                    //不能跟上面判断合并,不然报空指针
-                    continue;
-                }
-                for (int i = 1; i <= 26; i++) {
-                    boolean flag = (boolean) map.get("Alarm_unit_" + i);
-                    if (flag) {
-                        IndexAlarm indexAlarm = new IndexAlarm();
-                        indexAlarm.setCode(device.getDeviceCode());
-                        indexAlarm.setName(device.getDeviceName());
-                        indexAlarm.setType(i);
-                        alarmList.add(indexAlarm);
-                    }
-                }
-
-                int alarm27 = (int) map.get("Alarm_unit_27");
-                if (alarm27 != 0) {
-                    IndexAlarm indexAlarm = new IndexAlarm();
-                    indexAlarm.setCode(device.getDeviceCode());
-                    indexAlarm.setName(device.getDeviceName());
-                    indexAlarm.setType(27);
-                    alarmList.add(indexAlarm);
-                }
-
-                int stopStatus = (int) map.get("Capacity_data_48");
-                switch (stopStatus) {
-                    case 1:
-                        stop1++;
-                        break;
-                    case 2:
-                        stop2++;
-                        break;
-                    case 6:
-                        stop6++;
-                        break;
-                    default:
-                }
-
-                int[] curr = new int[5];
-                int[] max = new int[5];
-                float[] panPercent = new float[5];
-                for (int i = 0; i < curr.length; i++) {
-                    int pos = 15 + i;
-                    curr[i] = (int) map.get("Capacity_data_" + pos);
-                    String key = device.getId() + "_" + (i + 1);
-                    max[i] = 15000;
-                    if (panMap.get(key) != null) {
-                        max[i] = Math.toIntExact(panMap.get(key));
-                    }
-
-                    panPercent[i] = BigDecimal.valueOf(curr[i] * 100).divide(BigDecimal.valueOf(max[i]), 2, RoundingMode.HALF_UP).floatValue();
-                    if (panPercent[i] < 20) {
-                        stop8++;
-                    }
-                    if (panPercent[i] > 100) {
-                        panPercent[i] = 100;
-                    }
-                }
-
-                IndexPan pan = new IndexPan();
-                pan.setCode(device.getDeviceCode());
-                pan.setName(device.getDeviceName());
-                pan.setPanPercent(panPercent);
-                panList.add(pan);
-            }
-        } catch (InterruptedException e) {
-            throw new RuntimeException(e);
-        } catch (ExecutionException e) {
-            throw new RuntimeException(e);
+        Object d = CacheUtils.get(Constants.IOT_TOKEN, Constants.INDEX_ALARM);
+        if (d != null) {
+            IndexData indexData = (IndexData) d;
+            return R.ok(indexData);
+        } else {
+            return R.fail();
         }
-        indexData.setAlarm(alarmList);
-        indexData.setPan(panList);
-        IndexDevice device = new IndexDevice();
-        device.setTotal(Integer.parseInt(configService.selectConfigByKey("sys.device.total")));
-        device.setOnline(list.size());
-        device.setStop1(stop1);
-        device.setStop2(stop2);
-        device.setStop6(stop6);
-        device.setStop8(stop8);
-        device.setAlarm(alarmList.size());
-        indexData.setDevice(device);
-        return R.ok(indexData);
     }
 
     @ApiOperation("设备具体数据")

+ 17 - 0
ruoyi-admin/src/main/java/com/ruoyi/biz/service/IApiService.java

@@ -0,0 +1,17 @@
+package com.ruoyi.biz.service;
+
+/**
+ * 首页统计数据
+ * @author wukai
+ */
+public interface IApiService {
+    /**
+     * 首页统计数据
+     */
+    void indexCalc();
+
+    /**
+     * 首页告警数据
+     */
+    void indexAlarms();
+}

+ 198 - 0
ruoyi-admin/src/main/java/com/ruoyi/biz/service/impl/ApiServiceImpl.java

@@ -0,0 +1,198 @@
+package com.ruoyi.biz.service.impl;
+
+import com.ruoyi.biz.domain.*;
+import com.ruoyi.biz.service.*;
+import com.ruoyi.common.constant.Constants;
+import com.ruoyi.common.utils.CacheUtils;
+import com.ruoyi.system.service.ISysConfigService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.time.LocalDate;
+import java.time.ZoneOffset;
+import java.util.*;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+
+/**
+ * 首页统计数据
+ *
+ * @author wukai
+ * @date 2024/5/4 20:35
+ */
+@Service
+@Slf4j
+public class ApiServiceImpl implements IApiService {
+    @Resource
+    private ITwinCalcDayService twinCalcDayService;
+    @Resource
+    private ITwinCalc2hrService calc2hrService;
+    @Resource
+    private ITwinPanHeadInfoService panHeadInfoService;
+    @Resource
+    private ISysConfigService configService;
+    @Resource
+    private ITwinDeviceService deviceService;
+    @Resource
+    private IIotService iotService;
+    @Resource
+    private AsyncServiceImpl asyncService;
+
+    /**
+     * 首页统计数据
+     */
+    @Override
+    public void indexCalc() {
+        TwinCalc2hr calc2hr = calc2hrService.calcToday();
+        IndexData indexData = new IndexData();
+        IndexEfficiency efficiency = new IndexEfficiency(calc2hr);
+        indexData.setEfficiency(efficiency);
+        /*
+         *获取前面6天的数据,加上当天数据
+         */
+        LocalDate localDate = LocalDate.now().minusDays(6);
+        Date date = Date.from(localDate.atStartOfDay(ZoneOffset.of("+8")).toInstant());
+        List<TwinCalcDay> list = twinCalcDayService.selectTwinCalcDayListByTime(date);
+        TwinCalcDay today = new TwinCalcDay();
+        today.convert(calc2hr);
+        list.add(today);
+        List<WeekData> weekDataList = new ArrayList<>();
+        list.forEach(day -> {
+            WeekData weekData = new WeekData();
+            weekData.convert(day);
+            weekDataList.add(weekData);
+
+        });
+        indexData.setWeekData(weekDataList);
+        CacheUtils.put(Constants.IOT_TOKEN, Constants.INDEX_CALC, indexData);
+    }
+
+    /**
+     * 首页告警数据
+     */
+    @Override
+    public void indexAlarms() {
+        IndexData indexData = new IndexData();
+        List<IndexAlarm> alarmList = new ArrayList<>();
+        List<IndexPan> panList = new ArrayList<>();
+        int stop1 = 0, stop2 = 0, stop6 = 0, stop8 = 0;
+        iotService.getToken();
+        List<TwinDevice> list = deviceService.selectTwinDeviceList(new TwinDevice());
+        Map<String, Long> panMap = new HashMap<>(16);
+        panHeadInfoService.selectTwinPanHeadInfoList(new TwinPanHeadInfo()).forEach(pan -> {
+            String key = pan.getDeviceId() + "_" + pan.getPhNum();
+            panMap.put(key, pan.getPhMax());
+        });
+        List<Future<Map<String, Object>>> futureList = new ArrayList<>();
+        for (int i = 0; i < list.size(); i++) {
+            TwinDevice twinDevice = list.get(i);
+            futureList.add(asyncService.currData(twinDevice));
+        }
+        try {
+            for (Future<Map<String, Object>> future : futureList) {
+                Map<String, Object> map = future.get();
+                TwinDevice device = (TwinDevice) map.get("device");
+                int total = (int) map.get("total");
+                if (total == 0) {
+                    //可能会出现接口返回无数据的情况
+                    continue;
+                }
+                int data4 = (int) map.get("Capacity_data_4");
+                if (data4 == 0) {
+                    //Capacity_data_4,如果设定落布米数为0,则证明当前数据无效
+                    //不能跟上面判断合并,不然报空指针
+                    continue;
+                }
+                for (int i = 1; i <= 26; i++) {
+                    boolean flag = (boolean) map.get("Alarm_unit_" + i);
+                    if (flag) {
+                        if (i != 9) {
+                            //电源故障暂时先不展示
+                            IndexAlarm indexAlarm = new IndexAlarm();
+                            indexAlarm.setCode(device.getDeviceCode());
+                            indexAlarm.setName(device.getDeviceName());
+                            indexAlarm.setType(i);
+                            alarmList.add(indexAlarm);
+                        }
+                    }
+                }
+
+                int alarm27 = (int) map.get("Alarm_unit_27");
+                if (alarm27 != 0) {
+                    IndexAlarm indexAlarm = new IndexAlarm();
+                    indexAlarm.setCode(device.getDeviceCode());
+                    indexAlarm.setName(device.getDeviceName());
+                    indexAlarm.setType(27);
+                    alarmList.add(indexAlarm);
+                }
+
+                int stopStatus = (int) map.get("Capacity_data_48");
+                switch (stopStatus) {
+                    case 1:
+                        stop1++;
+                        break;
+                    case 2:
+                        stop2++;
+                        break;
+                    case 6:
+                        stop6++;
+                        break;
+                    default:
+                }
+
+                int[] curr = new int[5];
+                int[] max = new int[5];
+                float[] panPercent = new float[5];
+                for (int i = 0; i < curr.length; i++) {
+                    int pos = 15 + i;
+                    curr[i] = (int) map.get("Capacity_data_" + pos);
+                    String key = device.getId() + "_" + (i + 1);
+                    max[i] = 15000;
+                    if (panMap.get(key) != null) {
+                        max[i] = Math.toIntExact(panMap.get(key));
+                    }
+
+                    panPercent[i] = BigDecimal.valueOf(curr[i] * 100).divide(BigDecimal.valueOf(max[i]), 2, RoundingMode.HALF_UP).floatValue();
+                    if (panPercent[i] < 20) {
+                        stop8++;
+                    }
+                    if (panPercent[i] > 100) {
+                        panPercent[i] = 100;
+                    }
+                }
+
+                IndexPan pan = new IndexPan();
+                pan.setCode(device.getDeviceCode());
+                pan.setName(device.getDeviceName());
+                pan.setPanPercent(panPercent);
+                panList.add(pan);
+            }
+        } catch (InterruptedException e) {
+            throw new RuntimeException(e);
+        } catch (ExecutionException e) {
+            throw new RuntimeException(e);
+        }
+        indexData.setAlarm(alarmList);
+        indexData.setPan(panList);
+        IndexDevice device = new IndexDevice();
+        device.setTotal(Integer.parseInt(configService.selectConfigByKey("sys.device.total")));
+        device.setOnline(list.size());
+        device.setStop1(stop1);
+        device.setStop2(stop2);
+        device.setStop6(stop6);
+        device.setStop8(stop8);
+        device.setAlarm(alarmList.size());
+        indexData.setDevice(device);
+        CacheUtils.put(Constants.IOT_TOKEN, Constants.INDEX_ALARM, indexData);
+    }
+
+    @PostConstruct
+    public void init() {
+        indexCalc();
+        indexAlarms();
+    }
+}

+ 23 - 1
ruoyi-admin/src/main/java/com/ruoyi/biz/task/TwinTask.java

@@ -1,5 +1,6 @@
 package com.ruoyi.biz.task;
 
+import com.ruoyi.biz.service.IApiService;
 import com.ruoyi.biz.service.ITaskService;
 import com.ruoyi.biz.service.ITwinCalcDayService;
 import org.springframework.stereotype.Component;
@@ -17,13 +18,34 @@ public class TwinTask {
     private ITaskService taskService;
     @Resource
     private ITwinCalcDayService dayService;
+    @Resource
+    private IApiService apiService;
 
-
+    /**
+     * 计算上一个时段数据
+     */
     public void last() {
         taskService.calcLastPeriod();
     }
 
+    /**
+     * 统计昨日数据
+     */
     public void day() {
         dayService.calcYesterday();
     }
+
+    /**
+     * 首页统计数据
+     */
+    public void indexCalc() {
+        apiService.indexCalc();
+    }
+
+    /**
+     * 首页告警数据
+     */
+    public void indexAlarms() {
+        apiService.indexAlarms();
+    }
 }

+ 26 - 24
ruoyi-admin/src/main/resources/my-application.yml

@@ -1,3 +1,29 @@
+# 工业互联网平台接口地址
+iot:
+  uri: http://192.168.66.190:81
+  # 必须加引号,不然会转换类型
+  tenantId: "000000"
+  username: supplier
+  password: 123456
+  authorization: Basic c2FiZXI6c2FiZXJfc2VjcmV0
+#excel模板存放位置
+excel:
+  template: D:\SYSTEM\Desktop\temp\excel\template.xlsx
+
+# 项目相关配置
+ruoyi:
+  # 名称
+  name: RuoYi
+  # 版本
+  version: 4.7.8
+  # 版权年份
+  copyrightYear: 2024
+  # 实例演示开关
+  demoEnabled: false
+  # 文件路径 示例( Windows配置D:/ruoyi/uploadPath,Linux配置 /home/ruoyi/uploadPath)
+  profile: D:/twin/uploadPath
+  # 获取ip地址开关
+  addressEnabled: false
 # Spring配置
 spring:
   # 模板引擎
@@ -87,30 +113,6 @@ spring:
         wall:
           config:
             multi-statement-allow: true
-# 工业互联网平台接口地址
-iot:
-  uri: http://192.168.66.190:81
-  # 必须加引号,不然会转换类型
-  tenantId: "000000"
-  username: supplier
-  password: 123456
-  authorization: Basic c2FiZXI6c2FiZXJfc2VjcmV0
-
-# 项目相关配置
-ruoyi:
-  # 名称
-  name: RuoYi
-  # 版本
-  version: 4.7.8
-  # 版权年份
-  copyrightYear: 2024
-  # 实例演示开关
-  demoEnabled: false
-  # 文件路径 示例( Windows配置D:/ruoyi/uploadPath,Linux配置 /home/ruoyi/uploadPath)
-  profile: D:/ruoyi/uploadPath
-  # 获取ip地址开关
-  addressEnabled: false
-
 # 开发环境配置
 server:
   # 服务器的HTTP端口,默认为80

BIN
ruoyi-admin/src/main/resources/templates/template.xlsx


+ 9 - 0
ruoyi-common/src/main/java/com/ruoyi/common/constant/Constants.java

@@ -76,6 +76,15 @@ public class Constants {
      * iotToken缓存
      */
     public static final String IOT_TOKEN = "iotCache";
+
+    /**
+     * 首页统计缓存
+     */
+    public static final String INDEX_CALC = "indexCalc";
+    /**
+     * 首页告警缓存
+     */
+    public static final String INDEX_ALARM = "indexAlarm";
     /**
      * 参数管理 cache key
      */