DeviceOfflineCheckTask.java 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package com.zksy.telemetry.utils;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.http.HttpEntity;
  6. import org.springframework.http.HttpHeaders;
  7. import org.springframework.http.MediaType;
  8. import com.zksy.api.scheduling.RefreshableOfflineCheckTask;
  9. import org.springframework.stereotype.Component;
  10. import com.zksy.api.service.CollectionLastReceiptService;
  11. import org.springframework.web.client.RestTemplate;
  12. import java.util.Date;
  13. import java.util.Arrays;
  14. import java.util.Map;
  15. import java.util.Set;
  16. import java.util.concurrent.ConcurrentHashMap;
  17. @Component
  18. public class DeviceOfflineCheckTask extends RefreshableOfflineCheckTask {
  19. private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
  20. public static ConcurrentHashMap<String, Date> deviceLastReceiveTimeMap = new ConcurrentHashMap<>();
  21. private final Set<String> offlineDeviceSet = ConcurrentHashMap.newKeySet();
  22. /** 本实例已成功同步在线的设备;不能把尚未检测过离线当作已经在线。 */
  23. private final Set<String> onlineDeviceSet = ConcurrentHashMap.newKeySet();
  24. private final Object[] deviceLocks = new Object[128];
  25. public DeviceOfflineCheckTask() {
  26. Arrays.setAll(deviceLocks, i -> new Object());
  27. }
  28. @Autowired
  29. private RestTemplate restTemplate;
  30. @Autowired
  31. private CollectionLastReceiptService lastReceiptService;
  32. @Override
  33. public void checkDeviceOffline() {
  34. int timeoutMinutes = effectiveOfflineTimeoutMinutes();
  35. logger.info("离线巡检开始: collector=telemetry, timeoutMinutes={}, memoryDevices={}",
  36. timeoutMinutes, deviceLastReceiveTimeMap.size());
  37. if (lastReceiptService != null) {
  38. lastReceiptService.restore("telemetry", deviceLastReceiveTimeMap, offlineDeviceSet);
  39. }
  40. Date now = new Date();
  41. long timeoutMs = (long) timeoutMinutes * 60 * 1000;
  42. for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
  43. synchronized (deviceLock(entry.getKey())) {
  44. // 与在线更新串行,重新读取时间,避免用旧快照覆盖刚收到的上报。
  45. Date latest = deviceLastReceiveTimeMap.get(entry.getKey());
  46. if (latest == null || now.getTime() - latest.getTime() <= timeoutMs) continue;
  47. if (offlineDeviceSet.add(entry.getKey())) {
  48. if (!updateDeviceOnlineStatus(entry.getKey(), 0)) {
  49. offlineDeviceSet.remove(entry.getKey());
  50. continue;
  51. }
  52. onlineDeviceSet.remove(entry.getKey());
  53. logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), timeoutMinutes);
  54. }
  55. }
  56. }
  57. }
  58. public void markDeviceOnline(String deviceCode) {
  59. if (deviceCode == null || deviceCode.trim().isEmpty()) return;
  60. synchronized (deviceLock(deviceCode)) {
  61. // 仅在接口明确成功后缓存;新建默认离线的设备首次上报也会进入这里。
  62. if (!onlineDeviceSet.contains(deviceCode) && updateDeviceOnlineStatus(deviceCode, 1)) {
  63. onlineDeviceSet.add(deviceCode);
  64. offlineDeviceSet.remove(deviceCode);
  65. logger.info("设备 {} 已在线", deviceCode);
  66. }
  67. }
  68. }
  69. private Object deviceLock(String deviceCode) {
  70. return deviceLocks[(deviceCode.hashCode() & Integer.MAX_VALUE) % deviceLocks.length];
  71. }
  72. private boolean updateDeviceOnlineStatus(String deviceCode, int onlineStatus) {
  73. try {
  74. Map<String, Object> params = Map.of("deviceCode", deviceCode, "onlineStatus", onlineStatus);
  75. HttpHeaders headers = new HttpHeaders();
  76. headers.setContentType(MediaType.APPLICATION_JSON);
  77. HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, headers);
  78. Map<?, ?> response = restTemplate.postForObject("http://zk-api-service/equipmentStatus/updateOnlineStatus", request, Map.class);
  79. if (response == null || !Boolean.TRUE.equals(response.get("success"))) {
  80. logger.warn("在线状态同步未成功,下次重试: deviceCode={}, onlineStatus={}", deviceCode, onlineStatus);
  81. return false;
  82. }
  83. return true;
  84. } catch (Exception e) {
  85. logger.error("更新设备在线状态失败: deviceCode={}, onlineStatus={}", deviceCode, onlineStatus, e);
  86. return false;
  87. }
  88. }
  89. }