Browse Source

Merge remote-tracking branch 'origin/master'

zengy 2 months ago
parent
commit
25ee5595d8
19 changed files with 350 additions and 81 deletions
  1. 15 10
      audio-service/src/main/java/com/zksy/audio/utils/DeviceOfflineCheckTask.java
  2. 1 0
      audio-service/src/main/java/com/zksy/audio/utils/MessageHandler.java
  3. 7 3
      environment-service/src/main/java/com/zksy/environment/config/RSServerService.java
  4. 14 10
      environment-service/src/main/java/com/zksy/environment/utils/DeviceOfflineCheckTask.java
  5. 2 0
      firefighting-pressure-service/src/main/java/com/zksy/pressure/PressureApplication.java
  6. 14 11
      firefighting-pressure-service/src/main/java/com/zksy/pressure/utils/DeviceOfflineCheckTask.java
  7. 2 0
      flammable-gas-service/src/main/java/com/zksy/gas/GasApplication.java
  8. 14 9
      flammable-gas-service/src/main/java/com/zksy/gas/utils/DeviceOfflineCheckTask.java
  9. 1 0
      manhole-service/src/main/java/com/zksy/manhole/ManholeApplication.java
  10. 14 11
      manhole-service/src/main/java/com/zksy/manhole/utils/DeviceOfflineCheckTask.java
  11. 2 0
      radar-service/src/main/java/com/zksy/radar/RadarApplication.java
  12. 14 9
      radar-service/src/main/java/com/zksy/radar/utils/DeviceOfflineCheckTask.java
  13. 14 9
      telemetry-service/src/main/java/com/zksy/telemetry/utils/DeviceOfflineCheckTask.java
  14. 2 0
      water-level-service/src/main/java/com/zksy/water/WaterLevelApplication.java
  15. 14 9
      water-level-service/src/main/java/com/zksy/water/utils/DeviceOfflineCheckTask.java
  16. 11 0
      zk-api-service/src/main/java/com/zksy/api/domain/CollectionLastReceipt.java
  17. 35 0
      zk-api-service/src/main/java/com/zksy/api/mapper/CollectionLastReceiptMapper.java
  18. 138 0
      zk-api-service/src/main/java/com/zksy/api/scheduling/RefreshableOfflineCheckTask.java
  19. 36 0
      zk-api-service/src/main/java/com/zksy/api/service/CollectionLastReceiptService.java

+ 15 - 10
audio-service/src/main/java/com/zksy/audio/utils/DeviceOfflineCheckTask.java

@@ -3,12 +3,12 @@ package com.zksy.audio.utils;
 import org.slf4j.Logger;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.MediaType;
 import org.springframework.http.MediaType;
-import org.springframework.scheduling.annotation.Scheduled;
+import com.zksy.api.scheduling.RefreshableOfflineCheckTask;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
+import com.zksy.api.service.CollectionLastReceiptService;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.client.RestTemplate;
 
 
 import java.util.Date;
 import java.util.Date;
@@ -19,7 +19,7 @@ import java.time.Clock;
 import java.util.Arrays;
 import java.util.Arrays;
 
 
 @Component
 @Component
-public class DeviceOfflineCheckTask {
+public class DeviceOfflineCheckTask extends RefreshableOfflineCheckTask {
     private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
     private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
 
 
     public static ConcurrentHashMap<String, Date> deviceLastReceiveTimeMap = new ConcurrentHashMap<>();
     public static ConcurrentHashMap<String, Date> deviceLastReceiveTimeMap = new ConcurrentHashMap<>();
@@ -30,20 +30,25 @@ public class DeviceOfflineCheckTask {
     private Clock clock = Clock.systemUTC();
     private Clock clock = Clock.systemUTC();
 
 
     public DeviceOfflineCheckTask() {
     public DeviceOfflineCheckTask() {
+        super(1560);
         Arrays.setAll(deviceLocks, i -> new Object());
         Arrays.setAll(deviceLocks, i -> new Object());
     }
     }
 
 
     @Autowired
     @Autowired
     private RestTemplate restTemplate;
     private RestTemplate restTemplate;
+    @Autowired
+    private CollectionLastReceiptService lastReceiptService;
 
 
-    // 每24小时上传一次,用户确认额外允许2小时延迟。
-    @Value("${device.offline.timeout-minutes:1560}")
-    private int offlineTimeoutMinutes = 1560;
-
-    @Scheduled(fixedRateString = "${device.offline.check-interval-ms:300000}")
+    @Override
     public void checkDeviceOffline() {
     public void checkDeviceOffline() {
+        int timeoutMinutes = effectiveOfflineTimeoutMinutes();
+        logger.info("离线巡检开始: collector=audio, timeoutMinutes={}, memoryDevices={}",
+                timeoutMinutes, deviceLastReceiveTimeMap.size());
+        if (lastReceiptService != null) {
+            lastReceiptService.restore("audio", deviceLastReceiveTimeMap, offlineDeviceSet);
+        }
         Date now = new Date(clock.millis());
         Date now = new Date(clock.millis());
-        long timeoutMs = (long) offlineTimeoutMinutes * 60 * 1000;
+        long timeoutMs = (long) timeoutMinutes * 60 * 1000;
         for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
         for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
             synchronized (deviceLock(entry.getKey())) {
             synchronized (deviceLock(entry.getKey())) {
                 // 与在线恢复串行,且重新读取时间,避免旧快照把刚收到上报的设备置离线。
                 // 与在线恢复串行,且重新读取时间,避免旧快照把刚收到上报的设备置离线。
@@ -55,7 +60,7 @@ public class DeviceOfflineCheckTask {
                         continue;
                         continue;
                     }
                     }
                     onlineDeviceSet.remove(entry.getKey());
                     onlineDeviceSet.remove(entry.getKey());
-                    logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), offlineTimeoutMinutes);
+                    logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), timeoutMinutes);
                 }
                 }
             }
             }
         }
         }

+ 1 - 0
audio-service/src/main/java/com/zksy/audio/utils/MessageHandler.java

@@ -101,6 +101,7 @@ public class MessageHandler extends ChannelInboundHandlerAdapter {
             noise.setCenterFrequency(DataParser.calcCenterFrequency(file.toString()));
             noise.setCenterFrequency(DataParser.calcCenterFrequency(file.toString()));
             noise.setFilepath(relative);
             noise.setFilepath(relative);
             noise.setTs(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
             noise.setTs(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
+            noise.setCreateTime(new Date());
             requireSaved(service.save(noise));
             requireSaved(service.save(noise));
             saved = true;
             saved = true;
             info.setPath(relative);
             info.setPath(relative);

+ 7 - 3
environment-service/src/main/java/com/zksy/environment/config/RSServerService.java

@@ -244,9 +244,8 @@ public class RSServerService {
             return;
             return;
         }
         }
         String deviceId = String.valueOf(data.getDeviceId());
         String deviceId = String.valueOf(data.getDeviceId());
-        // 更新设备最后接收数据时间,并标记设备在线
-        DeviceOfflineCheckTask.deviceLastReceiveTimeMap.put(deviceId, new Date());
-        run(deviceId, "在线状态同步", () -> deviceOfflineCheckTask.markDeviceOnline(deviceId));
+        // 只有包含有效监测值的上报才能刷新在线时间;空节点/无效值不能无限续期。
+        boolean receivedValidNode = false;
         boolean hasAlarm = false;
         boolean hasAlarm = false;
         boolean evaluationCompleted = !data.getNodeList().isEmpty();
         boolean evaluationCompleted = !data.getNodeList().isEmpty();
         for (NodeData nd : data.getNodeList()) {
         for (NodeData nd : data.getNodeList()) {
@@ -286,6 +285,11 @@ public class RSServerService {
                 if (!Float.isFinite(finalValue)) {
                 if (!Float.isFinite(finalValue)) {
                     throw new IllegalArgumentException("节点数值不是有效数字");
                     throw new IllegalArgumentException("节点数值不是有效数字");
                 }
                 }
+                if (!receivedValidNode) {
+                    DeviceOfflineCheckTask.deviceLastReceiveTimeMap.put(deviceId, new Date());
+                    run(deviceId, "在线状态同步", () -> deviceOfflineCheckTask.markDeviceOnline(deviceId));
+                    receivedValidNode = true;
+                }
                 // 保留两位小数(核心处理)
                 // 保留两位小数(核心处理)
                 finalValue = Math.round(finalValue * 100) / 100.0f;
                 finalValue = Math.round(finalValue * 100) / 100.0f;
 
 

+ 14 - 10
environment-service/src/main/java/com/zksy/environment/utils/DeviceOfflineCheckTask.java

@@ -7,8 +7,9 @@ import org.springframework.beans.factory.annotation.Value;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.MediaType;
 import org.springframework.http.MediaType;
-import org.springframework.scheduling.annotation.Scheduled;
+import com.zksy.api.scheduling.RefreshableOfflineCheckTask;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
+import com.zksy.api.service.CollectionLastReceiptService;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.client.RestTemplate;
 
 
 import java.util.Date;
 import java.util.Date;
@@ -22,7 +23,7 @@ import java.util.concurrent.ConcurrentHashMap;
  * 通过 REST API 更新设备在线状态
  * 通过 REST API 更新设备在线状态
  */
  */
 @Component
 @Component
-public class DeviceOfflineCheckTask {
+public class DeviceOfflineCheckTask extends RefreshableOfflineCheckTask {
     private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
     private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
 
 
     /** 设备最后接收数据时间 */
     /** 设备最后接收数据时间 */
@@ -40,16 +41,19 @@ public class DeviceOfflineCheckTask {
 
 
     @Autowired
     @Autowired
     private RestTemplate restTemplate;
     private RestTemplate restTemplate;
+    @Autowired
+    private CollectionLastReceiptService lastReceiptService;
 
 
-    /** 离线判定超时,单位:分钟,默认30分钟 */
-    @Value("${device.offline.timeout-minutes:30}")
-    private int offlineTimeoutMinutes;
-
-    /** 检查间隔,单位:毫秒,默认5分钟 */
-    @Scheduled(fixedRateString = "${device.offline.check-interval-ms:300000}")
+    @Override
     public void checkDeviceOffline() {
     public void checkDeviceOffline() {
+        int timeoutMinutes = effectiveOfflineTimeoutMinutes();
+        logger.info("离线巡检开始: collector=environment, timeoutMinutes={}, memoryDevices={}",
+                timeoutMinutes, deviceLastReceiveTimeMap.size());
+        if (lastReceiptService != null) {
+            lastReceiptService.restore("environment", deviceLastReceiveTimeMap, offlineDeviceSet);
+        }
         Date now = new Date();
         Date now = new Date();
-        long timeoutMs = (long) offlineTimeoutMinutes * 60 * 1000;
+        long timeoutMs = (long) timeoutMinutes * 60 * 1000;
         for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
         for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
             synchronized (deviceLock(entry.getKey())) {
             synchronized (deviceLock(entry.getKey())) {
                 // 与在线更新串行,重新读取时间,避免用旧快照覆盖刚收到的上报。
                 // 与在线更新串行,重新读取时间,避免用旧快照覆盖刚收到的上报。
@@ -61,7 +65,7 @@ public class DeviceOfflineCheckTask {
                         continue;
                         continue;
                     }
                     }
                     onlineDeviceSet.remove(entry.getKey());
                     onlineDeviceSet.remove(entry.getKey());
-                    logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), offlineTimeoutMinutes);
+                    logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), timeoutMinutes);
                 }
                 }
             }
             }
         }
         }

+ 2 - 0
firefighting-pressure-service/src/main/java/com/zksy/pressure/PressureApplication.java

@@ -4,10 +4,12 @@ package com.zksy.pressure;
 import org.mybatis.spring.annotation.MapperScan;
 import org.mybatis.spring.annotation.MapperScan;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.scheduling.annotation.EnableScheduling;
 import org.springframework.scheduling.annotation.EnableAsync;
 import org.springframework.scheduling.annotation.EnableAsync;
 
 
 //@MapperScan(basePackages = "com.zksy.pressure.mapper")
 //@MapperScan(basePackages = "com.zksy.pressure.mapper")
 //@SpringBootApplication(scanBasePackages = {"com.zksy.pressure","com.zksy.api"})
 //@SpringBootApplication(scanBasePackages = {"com.zksy.pressure","com.zksy.api"})
+@EnableScheduling
 @MapperScan({
 @MapperScan({
         "com.zksy.pressure.mapper",
         "com.zksy.pressure.mapper",
         "com.zksy.base.mapper",
         "com.zksy.base.mapper",

+ 14 - 11
firefighting-pressure-service/src/main/java/com/zksy/pressure/utils/DeviceOfflineCheckTask.java

@@ -3,12 +3,12 @@ package com.zksy.pressure.utils;
 import org.slf4j.Logger;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.MediaType;
 import org.springframework.http.MediaType;
-import org.springframework.scheduling.annotation.Scheduled;
+import com.zksy.api.scheduling.RefreshableOfflineCheckTask;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
+import com.zksy.api.service.CollectionLastReceiptService;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.client.RestTemplate;
 
 
 import java.util.Date;
 import java.util.Date;
@@ -22,7 +22,7 @@ import java.util.concurrent.ConcurrentHashMap;
  * 通过 REST API 更新设备在线状态
  * 通过 REST API 更新设备在线状态
  */
  */
 @Component
 @Component
-public class DeviceOfflineCheckTask {
+public class DeviceOfflineCheckTask extends RefreshableOfflineCheckTask {
     private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
     private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
 
 
     /** 设备最后接收数据时间 */
     /** 设备最后接收数据时间 */
@@ -40,16 +40,19 @@ public class DeviceOfflineCheckTask {
 
 
     @Autowired
     @Autowired
     private RestTemplate restTemplate;
     private RestTemplate restTemplate;
+    @Autowired
+    private CollectionLastReceiptService lastReceiptService;
 
 
-    /** 离线判定超时,单位:分钟,默认30分钟 */
-    @Value("${device.offline.timeout-minutes:30}")
-    private int offlineTimeoutMinutes = 30;
-
-    /** 检查间隔,单位:毫秒,默认5分钟 */
-    @Scheduled(fixedRateString = "${device.offline.check-interval-ms:300000}")
+    @Override
     public void checkDeviceOffline() {
     public void checkDeviceOffline() {
+        int timeoutMinutes = effectiveOfflineTimeoutMinutes();
+        logger.info("离线巡检开始: collector=pressure, timeoutMinutes={}, memoryDevices={}",
+                timeoutMinutes, deviceLastReceiveTimeMap.size());
+        if (lastReceiptService != null) {
+            lastReceiptService.restore("pressure", deviceLastReceiveTimeMap, offlineDeviceSet);
+        }
         Date now = new Date();
         Date now = new Date();
-        long timeoutMs = (long) offlineTimeoutMinutes * 60 * 1000;
+        long timeoutMs = (long) timeoutMinutes * 60 * 1000;
         for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
         for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
             synchronized (deviceLock(entry.getKey())) {
             synchronized (deviceLock(entry.getKey())) {
                 // 与在线更新串行,重新读取时间,避免用旧快照覆盖刚收到的上报。
                 // 与在线更新串行,重新读取时间,避免用旧快照覆盖刚收到的上报。
@@ -61,7 +64,7 @@ public class DeviceOfflineCheckTask {
                         continue;
                         continue;
                     }
                     }
                     onlineDeviceSet.remove(entry.getKey());
                     onlineDeviceSet.remove(entry.getKey());
-                    logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), offlineTimeoutMinutes);
+                    logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), timeoutMinutes);
                 }
                 }
             }
             }
         }
         }

+ 2 - 0
flammable-gas-service/src/main/java/com/zksy/gas/GasApplication.java

@@ -4,9 +4,11 @@ package com.zksy.gas;
 import org.mybatis.spring.annotation.MapperScan;
 import org.mybatis.spring.annotation.MapperScan;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.scheduling.annotation.EnableScheduling;
 
 
 //@MapperScan(basePackages = "com.zksy.gas.mapper")
 //@MapperScan(basePackages = "com.zksy.gas.mapper")
 //@SpringBootApplication(scanBasePackages = {"com.zksy.gas","com.zksy.api"})
 //@SpringBootApplication(scanBasePackages = {"com.zksy.gas","com.zksy.api"})
+@EnableScheduling
 @MapperScan({
 @MapperScan({
         "com.zksy.gas.mapper",
         "com.zksy.gas.mapper",
         "com.zksy.base.mapper",
         "com.zksy.base.mapper",

+ 14 - 9
flammable-gas-service/src/main/java/com/zksy/gas/utils/DeviceOfflineCheckTask.java

@@ -3,12 +3,12 @@ package com.zksy.gas.utils;
 import org.slf4j.Logger;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.MediaType;
 import org.springframework.http.MediaType;
-import org.springframework.scheduling.annotation.Scheduled;
+import com.zksy.api.scheduling.RefreshableOfflineCheckTask;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
+import com.zksy.api.service.CollectionLastReceiptService;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.client.RestTemplate;
 
 
 import java.util.Date;
 import java.util.Date;
@@ -18,7 +18,7 @@ import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentHashMap;
 
 
 @Component
 @Component
-public class DeviceOfflineCheckTask {
+public class DeviceOfflineCheckTask extends RefreshableOfflineCheckTask {
     private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
     private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
 
 
     public static ConcurrentHashMap<String, Date> deviceLastReceiveTimeMap = new ConcurrentHashMap<>();
     public static ConcurrentHashMap<String, Date> deviceLastReceiveTimeMap = new ConcurrentHashMap<>();
@@ -34,14 +34,19 @@ public class DeviceOfflineCheckTask {
 
 
     @Autowired
     @Autowired
     private RestTemplate restTemplate;
     private RestTemplate restTemplate;
+    @Autowired
+    private CollectionLastReceiptService lastReceiptService;
 
 
-    @Value("${device.offline.timeout-minutes:30}")
-    private int offlineTimeoutMinutes = 30;
-
-    @Scheduled(fixedRateString = "${device.offline.check-interval-ms:300000}")
+    @Override
     public void checkDeviceOffline() {
     public void checkDeviceOffline() {
+        int timeoutMinutes = effectiveOfflineTimeoutMinutes();
+        logger.info("离线巡检开始: collector=gas, timeoutMinutes={}, memoryDevices={}",
+                timeoutMinutes, deviceLastReceiveTimeMap.size());
+        if (lastReceiptService != null) {
+            lastReceiptService.restore("gas", deviceLastReceiveTimeMap, offlineDeviceSet);
+        }
         Date now = new Date();
         Date now = new Date();
-        long timeoutMs = (long) offlineTimeoutMinutes * 60 * 1000;
+        long timeoutMs = (long) timeoutMinutes * 60 * 1000;
         for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
         for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
             synchronized (deviceLock(entry.getKey())) {
             synchronized (deviceLock(entry.getKey())) {
                 // 与在线更新串行,重新读取时间,避免用旧快照覆盖刚收到的上报。
                 // 与在线更新串行,重新读取时间,避免用旧快照覆盖刚收到的上报。
@@ -53,7 +58,7 @@ public class DeviceOfflineCheckTask {
                         continue;
                         continue;
                     }
                     }
                     onlineDeviceSet.remove(entry.getKey());
                     onlineDeviceSet.remove(entry.getKey());
-                    logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), offlineTimeoutMinutes);
+                    logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), timeoutMinutes);
                 }
                 }
             }
             }
         }
         }

+ 1 - 0
manhole-service/src/main/java/com/zksy/manhole/ManholeApplication.java

@@ -5,6 +5,7 @@ import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.scheduling.annotation.EnableScheduling;
 import org.springframework.scheduling.annotation.EnableScheduling;
 
 
+@EnableScheduling
 @MapperScan({
 @MapperScan({
         "com.zksy.manhole.mapper",
         "com.zksy.manhole.mapper",
         "com.zksy.base.mapper",
         "com.zksy.base.mapper",

+ 14 - 11
manhole-service/src/main/java/com/zksy/manhole/utils/DeviceOfflineCheckTask.java

@@ -3,12 +3,12 @@ package com.zksy.manhole.utils;
 import org.slf4j.Logger;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.MediaType;
 import org.springframework.http.MediaType;
-import org.springframework.scheduling.annotation.Scheduled;
+import com.zksy.api.scheduling.RefreshableOfflineCheckTask;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
+import com.zksy.api.service.CollectionLastReceiptService;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.client.RestTemplate;
 
 
 import java.util.Date;
 import java.util.Date;
@@ -22,7 +22,7 @@ import java.util.concurrent.ConcurrentHashMap;
  * 通过 REST API 更新设备在线状态
  * 通过 REST API 更新设备在线状态
  */
  */
 @Component
 @Component
-public class DeviceOfflineCheckTask {
+public class DeviceOfflineCheckTask extends RefreshableOfflineCheckTask {
     private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
     private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
 
 
     /** 设备最后接收数据时间 */
     /** 设备最后接收数据时间 */
@@ -40,16 +40,19 @@ public class DeviceOfflineCheckTask {
 
 
     @Autowired
     @Autowired
     private RestTemplate restTemplate;
     private RestTemplate restTemplate;
+    @Autowired
+    private CollectionLastReceiptService lastReceiptService;
 
 
-    /** 离线判定超时,单位:分钟,默认30分钟 */
-    @Value("${device.offline.timeout-minutes:30}")
-    private int offlineTimeoutMinutes = 30;
-
-    /** 检查间隔,单位:毫秒,默认5分钟 */
-    @Scheduled(fixedRateString = "${device.offline.check-interval-ms:300000}")
+    @Override
     public void checkDeviceOffline() {
     public void checkDeviceOffline() {
+        int timeoutMinutes = effectiveOfflineTimeoutMinutes();
+        logger.info("离线巡检开始: collector=manhole, timeoutMinutes={}, memoryDevices={}",
+                timeoutMinutes, deviceLastReceiveTimeMap.size());
+        if (lastReceiptService != null) {
+            lastReceiptService.restore("manhole", deviceLastReceiveTimeMap, offlineDeviceSet);
+        }
         Date now = new Date();
         Date now = new Date();
-        long timeoutMs = (long) offlineTimeoutMinutes * 60 * 1000;
+        long timeoutMs = (long) timeoutMinutes * 60 * 1000;
         for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
         for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
             synchronized (deviceLock(entry.getKey())) {
             synchronized (deviceLock(entry.getKey())) {
                 // 与在线更新串行,重新读取时间,避免用旧快照覆盖刚收到的上报。
                 // 与在线更新串行,重新读取时间,避免用旧快照覆盖刚收到的上报。
@@ -61,7 +64,7 @@ public class DeviceOfflineCheckTask {
                         continue;
                         continue;
                     }
                     }
                     onlineDeviceSet.remove(entry.getKey());
                     onlineDeviceSet.remove(entry.getKey());
-                    logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), offlineTimeoutMinutes);
+                    logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), timeoutMinutes);
                 }
                 }
             }
             }
         }
         }

+ 2 - 0
radar-service/src/main/java/com/zksy/radar/RadarApplication.java

@@ -4,7 +4,9 @@ package com.zksy.radar;
 import org.mybatis.spring.annotation.MapperScan;
 import org.mybatis.spring.annotation.MapperScan;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.scheduling.annotation.EnableScheduling;
 
 
+@EnableScheduling
 @MapperScan({
 @MapperScan({
         "com.zksy.radar.mapper",
         "com.zksy.radar.mapper",
         "com.zksy.base.mapper",
         "com.zksy.base.mapper",

+ 14 - 9
radar-service/src/main/java/com/zksy/radar/utils/DeviceOfflineCheckTask.java

@@ -3,12 +3,12 @@ package com.zksy.radar.utils;
 import org.slf4j.Logger;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.MediaType;
 import org.springframework.http.MediaType;
-import org.springframework.scheduling.annotation.Scheduled;
+import com.zksy.api.scheduling.RefreshableOfflineCheckTask;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
+import com.zksy.api.service.CollectionLastReceiptService;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.client.RestTemplate;
 
 
 import java.util.Date;
 import java.util.Date;
@@ -18,7 +18,7 @@ import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentHashMap;
 
 
 @Component
 @Component
-public class DeviceOfflineCheckTask {
+public class DeviceOfflineCheckTask extends RefreshableOfflineCheckTask {
     private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
     private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
 
 
     public static ConcurrentHashMap<String, Date> deviceLastReceiveTimeMap = new ConcurrentHashMap<>();
     public static ConcurrentHashMap<String, Date> deviceLastReceiveTimeMap = new ConcurrentHashMap<>();
@@ -34,14 +34,19 @@ public class DeviceOfflineCheckTask {
 
 
     @Autowired
     @Autowired
     private RestTemplate restTemplate;
     private RestTemplate restTemplate;
+    @Autowired
+    private CollectionLastReceiptService lastReceiptService;
 
 
-    @Value("${device.offline.timeout-minutes:30}")
-    private int offlineTimeoutMinutes = 30;
-
-    @Scheduled(fixedRateString = "${device.offline.check-interval-ms:300000}")
+    @Override
     public void checkDeviceOffline() {
     public void checkDeviceOffline() {
+        int timeoutMinutes = effectiveOfflineTimeoutMinutes();
+        logger.info("离线巡检开始: collector=radar, timeoutMinutes={}, memoryDevices={}",
+                timeoutMinutes, deviceLastReceiveTimeMap.size());
+        if (lastReceiptService != null) {
+            lastReceiptService.restore("radar", deviceLastReceiveTimeMap, offlineDeviceSet);
+        }
         Date now = new Date();
         Date now = new Date();
-        long timeoutMs = (long) offlineTimeoutMinutes * 60 * 1000;
+        long timeoutMs = (long) timeoutMinutes * 60 * 1000;
         for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
         for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
             synchronized (deviceLock(entry.getKey())) {
             synchronized (deviceLock(entry.getKey())) {
                 // 与在线更新串行,重新读取时间,避免用旧快照覆盖刚收到的上报。
                 // 与在线更新串行,重新读取时间,避免用旧快照覆盖刚收到的上报。
@@ -53,7 +58,7 @@ public class DeviceOfflineCheckTask {
                         continue;
                         continue;
                     }
                     }
                     onlineDeviceSet.remove(entry.getKey());
                     onlineDeviceSet.remove(entry.getKey());
-                    logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), offlineTimeoutMinutes);
+                    logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), timeoutMinutes);
                 }
                 }
             }
             }
         }
         }

+ 14 - 9
telemetry-service/src/main/java/com/zksy/telemetry/utils/DeviceOfflineCheckTask.java

@@ -3,12 +3,12 @@ package com.zksy.telemetry.utils;
 import org.slf4j.Logger;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.MediaType;
 import org.springframework.http.MediaType;
-import org.springframework.scheduling.annotation.Scheduled;
+import com.zksy.api.scheduling.RefreshableOfflineCheckTask;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
+import com.zksy.api.service.CollectionLastReceiptService;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.client.RestTemplate;
 
 
 import java.util.Date;
 import java.util.Date;
@@ -18,7 +18,7 @@ import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentHashMap;
 
 
 @Component
 @Component
-public class DeviceOfflineCheckTask {
+public class DeviceOfflineCheckTask extends RefreshableOfflineCheckTask {
     private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
     private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
 
 
     public static ConcurrentHashMap<String, Date> deviceLastReceiveTimeMap = new ConcurrentHashMap<>();
     public static ConcurrentHashMap<String, Date> deviceLastReceiveTimeMap = new ConcurrentHashMap<>();
@@ -34,14 +34,19 @@ public class DeviceOfflineCheckTask {
 
 
     @Autowired
     @Autowired
     private RestTemplate restTemplate;
     private RestTemplate restTemplate;
+    @Autowired
+    private CollectionLastReceiptService lastReceiptService;
 
 
-    @Value("${device.offline.timeout-minutes:30}")
-    private int offlineTimeoutMinutes = 30;
-
-    @Scheduled(fixedRateString = "${device.offline.check-interval-ms:300000}")
+    @Override
     public void checkDeviceOffline() {
     public void checkDeviceOffline() {
+        int timeoutMinutes = effectiveOfflineTimeoutMinutes();
+        logger.info("离线巡检开始: collector=telemetry, timeoutMinutes={}, memoryDevices={}",
+                timeoutMinutes, deviceLastReceiveTimeMap.size());
+        if (lastReceiptService != null) {
+            lastReceiptService.restore("telemetry", deviceLastReceiveTimeMap, offlineDeviceSet);
+        }
         Date now = new Date();
         Date now = new Date();
-        long timeoutMs = (long) offlineTimeoutMinutes * 60 * 1000;
+        long timeoutMs = (long) timeoutMinutes * 60 * 1000;
         for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
         for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
             synchronized (deviceLock(entry.getKey())) {
             synchronized (deviceLock(entry.getKey())) {
                 // 与在线更新串行,重新读取时间,避免用旧快照覆盖刚收到的上报。
                 // 与在线更新串行,重新读取时间,避免用旧快照覆盖刚收到的上报。
@@ -53,7 +58,7 @@ public class DeviceOfflineCheckTask {
                         continue;
                         continue;
                     }
                     }
                     onlineDeviceSet.remove(entry.getKey());
                     onlineDeviceSet.remove(entry.getKey());
-                    logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), offlineTimeoutMinutes);
+                    logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), timeoutMinutes);
                 }
                 }
             }
             }
         }
         }

+ 2 - 0
water-level-service/src/main/java/com/zksy/water/WaterLevelApplication.java

@@ -4,7 +4,9 @@ package com.zksy.water;
 import org.mybatis.spring.annotation.MapperScan;
 import org.mybatis.spring.annotation.MapperScan;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.scheduling.annotation.EnableScheduling;
 
 
+@EnableScheduling
 @MapperScan({
 @MapperScan({
         "com.zksy.water.mapper",
         "com.zksy.water.mapper",
         "com.zksy.base.mapper",
         "com.zksy.base.mapper",

+ 14 - 9
water-level-service/src/main/java/com/zksy/water/utils/DeviceOfflineCheckTask.java

@@ -3,12 +3,12 @@ package com.zksy.water.utils;
 import org.slf4j.Logger;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.MediaType;
 import org.springframework.http.MediaType;
-import org.springframework.scheduling.annotation.Scheduled;
+import com.zksy.api.scheduling.RefreshableOfflineCheckTask;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
+import com.zksy.api.service.CollectionLastReceiptService;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.client.RestTemplate;
 
 
 import java.util.Date;
 import java.util.Date;
@@ -18,7 +18,7 @@ import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentHashMap;
 
 
 @Component
 @Component
-public class DeviceOfflineCheckTask {
+public class DeviceOfflineCheckTask extends RefreshableOfflineCheckTask {
     private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
     private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
 
 
     public static ConcurrentHashMap<String, Date> deviceLastReceiveTimeMap = new ConcurrentHashMap<>();
     public static ConcurrentHashMap<String, Date> deviceLastReceiveTimeMap = new ConcurrentHashMap<>();
@@ -34,14 +34,19 @@ public class DeviceOfflineCheckTask {
 
 
     @Autowired
     @Autowired
     private RestTemplate restTemplate;
     private RestTemplate restTemplate;
+    @Autowired
+    private CollectionLastReceiptService lastReceiptService;
 
 
-    @Value("${device.offline.timeout-minutes:30}")
-    private int offlineTimeoutMinutes = 30;
-
-    @Scheduled(fixedRateString = "${device.offline.check-interval-ms:300000}")
+    @Override
     public void checkDeviceOffline() {
     public void checkDeviceOffline() {
+        int timeoutMinutes = effectiveOfflineTimeoutMinutes();
+        logger.info("离线巡检开始: collector=water, timeoutMinutes={}, memoryDevices={}",
+                timeoutMinutes, deviceLastReceiveTimeMap.size());
+        if (lastReceiptService != null) {
+            lastReceiptService.restore("water", deviceLastReceiveTimeMap, offlineDeviceSet);
+        }
         Date now = new Date();
         Date now = new Date();
-        long timeoutMs = (long) offlineTimeoutMinutes * 60 * 1000;
+        long timeoutMs = (long) timeoutMinutes * 60 * 1000;
         for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
         for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
             synchronized (deviceLock(entry.getKey())) {
             synchronized (deviceLock(entry.getKey())) {
                 // 与在线更新串行,重新读取时间,避免用旧快照覆盖刚收到的上报。
                 // 与在线更新串行,重新读取时间,避免用旧快照覆盖刚收到的上报。
@@ -53,7 +58,7 @@ public class DeviceOfflineCheckTask {
                         continue;
                         continue;
                     }
                     }
                     onlineDeviceSet.remove(entry.getKey());
                     onlineDeviceSet.remove(entry.getKey());
-                    logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), offlineTimeoutMinutes);
+                    logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), timeoutMinutes);
                 }
                 }
             }
             }
         }
         }

+ 11 - 0
zk-api-service/src/main/java/com/zksy/api/domain/CollectionLastReceipt.java

@@ -0,0 +1,11 @@
+package com.zksy.api.domain;
+
+import lombok.Data;
+import java.util.Date;
+
+/** 采集表中已保存的最后接收时间,用于服务重启后恢复离线检测。 */
+@Data
+public class CollectionLastReceipt {
+    private String deviceCode;
+    private Date lastReceiveTime;
+}

+ 35 - 0
zk-api-service/src/main/java/com/zksy/api/mapper/CollectionLastReceiptMapper.java

@@ -0,0 +1,35 @@
+package com.zksy.api.mapper;
+
+import com.zksy.api.domain.CollectionLastReceipt;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.Select;
+import org.apache.ibatis.annotations.Result;
+import org.apache.ibatis.annotations.Results;
+import org.apache.ibatis.annotations.Options;
+import java.util.List;
+
+public interface CollectionLastReceiptMapper {
+    /** 仅恢复本类采集表里有记录且台账仍在线的设备;表名和列名均为固定白名单。 */
+    @Select({"<script>",
+            "SELECT r.device_code, MAX(r.received_at) AS last_receive_time FROM (",
+            "<choose>",
+            "<when test=\"collector == 'environment'\">SELECT CAST(device_id AS varchar) AS device_code, create_time AS received_at FROM app_user.e_real_time_data</when>",
+            "<when test=\"collector == 'gas'\">SELECT mac_address AS device_code, create_time AS received_at FROM app_user.gas_monitor_data</when>",
+            "<when test=\"collector == 'pressure'\">SELECT telemetering_station AS device_code, create_time AS received_at FROM app_user.firefighting_pressure</when>",
+            "<when test=\"collector == 'manhole'\">SELECT imei_card_number AS device_code, create_time AS received_at FROM app_user.jg_device_data</when>",
+            "<when test=\"collector == 'radar'\">SELECT device_code, create_time AS received_at FROM app_user.radar_data</when>",
+            "<when test=\"collector == 'telemetry'\">SELECT device_code, create_time AS received_at FROM app_user.telemetry_data</when>",
+            "<when test=\"collector == 'water'\">SELECT device_code, create_time AS received_at FROM app_user.water_monitor_data</when>",
+            "<when test=\"collector == 'audio'\">SELECT encode AS device_code, COALESCE(create_time, CASE WHEN ts ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$' THEN CAST(ts AS timestamp) END) AS received_at FROM app_user.noise_info</when>",
+            "<otherwise>SELECT CAST(NULL AS varchar) AS device_code, CAST(NULL AS timestamp) AS received_at WHERE 1=0</otherwise>",
+            "</choose>",
+            ") r WHERE r.received_at IS NOT NULL AND EXISTS (",
+            "SELECT 1 FROM app_user.equipment_base b JOIN app_user.equipment_status s ON s.equipment_id=b.equipment_id",
+            "WHERE b.equipment_code=r.device_code AND s.online_status=1 AND COALESCE(b.del_flag,'0')='0' AND COALESCE(s.del_flag,'0')='0'",
+            ") GROUP BY r.device_code",
+            "</script>"})
+    @Results({@Result(column = "device_code", property = "deviceCode"),
+            @Result(column = "last_receive_time", property = "lastReceiveTime")})
+    @Options(timeout = 15)
+    List<CollectionLastReceipt> selectOnlineLastReceipts(@Param("collector") String collector);
+}

+ 138 - 0
zk-api-service/src/main/java/com/zksy/api/scheduling/RefreshableOfflineCheckTask.java

@@ -0,0 +1,138 @@
+package com.zksy.api.scheduling;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.DisposableBean;
+import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+import org.springframework.context.ApplicationEvent;
+import org.springframework.context.ApplicationListener;
+import org.springframework.context.EnvironmentAware;
+import org.springframework.context.event.ContextRefreshedEvent;
+import org.springframework.core.env.Environment;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
+
+import java.util.Objects;
+import java.util.concurrent.ScheduledFuture;
+
+/**
+ * Nacos刷新后重新读取离线参数并重排巡检,不重建有设备状态缓存的任务bean。
+ * 每个采集实例仅使用一条调度线程,刷新时不打断正在执行的巡检,也不会并发巡检。
+ */
+public abstract class RefreshableOfflineCheckTask implements EnvironmentAware, ApplicationContextAware,
+        ApplicationListener<ApplicationEvent>, DisposableBean {
+    private static final Logger log = LoggerFactory.getLogger(RefreshableOfflineCheckTask.class);
+    private static final String TIMEOUT_KEY = "device.offline.timeout-minutes";
+    private static final String INTERVAL_KEY = "device.offline.check-interval-ms";
+    private static final long DEFAULT_INTERVAL_MS = 300000;
+
+    /** 未显式配置时使用的服务默认值;音频通过构造器设为1560分钟。 */
+    protected int offlineTimeoutMinutes;
+    private final Object lifecycleLock = new Object();
+    private final PositiveSetting timeoutSetting;
+    private final PositiveSetting intervalSetting = new PositiveSetting(INTERVAL_KEY, DEFAULT_INTERVAL_MS, Long.MAX_VALUE);
+    private Environment environment;
+    private ApplicationContext applicationContext;
+    private ThreadPoolTaskScheduler scheduler;
+    private ScheduledFuture<?> scheduled;
+    private long scheduledIntervalMs;
+    private int scheduledTimeoutMinutes;
+    private boolean closed;
+
+    protected RefreshableOfflineCheckTask() { this(30); }
+
+    protected RefreshableOfflineCheckTask(int defaultTimeoutMinutes) {
+        offlineTimeoutMinutes = defaultTimeoutMinutes;
+        timeoutSetting = new PositiveSetting(TIMEOUT_KEY, defaultTimeoutMinutes, Integer.MAX_VALUE);
+    }
+
+    @Override public void setEnvironment(Environment environment) { this.environment = environment; }
+    @Override public void setApplicationContext(ApplicationContext context) { applicationContext = context; }
+
+    /** 每轮读取当前Environment,避免普通@Value字段在Nacos刷新后仍保留启动值。 */
+    protected final int effectiveOfflineTimeoutMinutes() {
+        synchronized (lifecycleLock) {
+            return (int) timeoutSetting.read(environment, offlineTimeoutMinutes);
+        }
+    }
+
+    @Override public final void onApplicationEvent(ApplicationEvent event) {
+        if (event instanceof ContextRefreshedEvent
+                && ((ContextRefreshedEvent) event).getApplicationContext() == applicationContext) {
+            configureSchedule(true);
+        } else if (event instanceof EnvironmentChangeEvent) {
+            EnvironmentChangeEvent changed = (EnvironmentChangeEvent) event;
+            if (changed.getKeys().contains(TIMEOUT_KEY) || changed.getKeys().contains(INTERVAL_KEY)) {
+                configureSchedule(false);
+            }
+        }
+    }
+
+    private void configureSchedule(boolean starting) {
+        synchronized (lifecycleLock) {
+            if (closed || (scheduler == null && !starting)) return;
+            int timeout = effectiveOfflineTimeoutMinutes();
+            long interval = intervalSetting.read(environment, DEFAULT_INTERVAL_MS);
+            if (scheduler != null && scheduledTimeoutMinutes == timeout && scheduledIntervalMs == interval) return;
+            if (scheduler == null) {
+                scheduler = new ThreadPoolTaskScheduler();
+                scheduler.setPoolSize(1);
+                scheduler.setThreadNamePrefix("offline-" + getClass().getPackageName().split("\\.")[2] + "-");
+                scheduler.setRemoveOnCancelPolicy(true);
+                scheduler.setAwaitTerminationSeconds(3);
+                scheduler.initialize();
+            }
+            if (scheduled != null) scheduled.cancel(false);
+            // 从现在开始按新值执行;缩短超时后不再等待旧间隔到期。
+            scheduled = scheduler.scheduleAtFixedRate(this::checkDeviceOffline, interval);
+            scheduledTimeoutMinutes = timeout;
+            scheduledIntervalMs = interval;
+            log.info("离线巡检配置生效: task={}, timeoutMinutes={}, checkIntervalMs={}",
+                    getClass().getName(), timeout, interval);
+        }
+    }
+
+    public abstract void checkDeviceOffline();
+
+    @Override public final void destroy() {
+        ThreadPoolTaskScheduler previous;
+        synchronized (lifecycleLock) {
+            closed = true;
+            if (scheduled != null) scheduled.cancel(false);
+            previous = scheduler;
+            scheduler = null;
+        }
+        if (previous != null) previous.shutdown();
+    }
+
+    /** 非法配置保留最近有效值,防止0/负数令全部设备离线或让定时任务终止。 */
+    private static final class PositiveSetting {
+        private final String key;
+        private final long max;
+        private long lastValid;
+        private String lastInvalid;
+
+        private PositiveSetting(String key, long initial, long max) {
+            this.key = key; this.lastValid = initial; this.max = max;
+        }
+
+        private long read(Environment environment, long fallback) {
+            String raw = environment == null ? null : environment.getProperty(key);
+            if (raw == null) {
+                lastValid = fallback; lastInvalid = null; return fallback;
+            }
+            try {
+                long value = Long.parseLong(raw.trim());
+                if (value <= 0 || value > max) throw new NumberFormatException();
+                lastValid = value; lastInvalid = null; return value;
+            } catch (NumberFormatException e) {
+                if (!Objects.equals(raw, lastInvalid)) {
+                    log.warn("离线巡检参数必须为有效正整数,沿用最近有效值: key={}, effectiveValue={}", key, lastValid);
+                    lastInvalid = raw;
+                }
+                return lastValid;
+            }
+        }
+    }
+}

+ 36 - 0
zk-api-service/src/main/java/com/zksy/api/service/CollectionLastReceiptService.java

@@ -0,0 +1,36 @@
+package com.zksy.api.service;
+
+import com.zksy.api.domain.CollectionLastReceipt;
+import com.zksy.api.mapper.CollectionLastReceiptMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import java.util.Date;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ConcurrentMap;
+
+@Slf4j
+@Service
+public class CollectionLastReceiptService {
+    @Autowired private CollectionLastReceiptMapper mapper;
+
+    /** 每轮重查数据库,补齐重启丢失的设备,并合并其他实例已保存的更新上报。 */
+    public void restore(String collector, ConcurrentMap<String, Date> received,
+                        Set<String> offlineDevices) {
+        try {
+            List<CollectionLastReceipt> rows = mapper.selectOnlineLastReceipts(collector);
+            if (rows == null) return;
+            for (CollectionLastReceipt row : rows) {
+                if (row == null || row.getDeviceCode() == null || row.getDeviceCode().trim().isEmpty()
+                        || row.getLastReceiveTime() == null) continue;
+                received.merge(row.getDeviceCode(), row.getLastReceiveTime(), (local, saved) ->
+                        local.after(saved) ? local : saved);
+                // 数据库仍是在线时不能仅因本地已处理过离线而永久跳过。
+                offlineDevices.remove(row.getDeviceCode());
+            }
+        } catch (Exception e) {
+            log.error("恢复离线检测名单失败,本轮继续检查本地已知设备,下轮重试: collector={}", collector, e);
+        }
+    }
+}