DeviceOfflineCheckTask.java 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package com.zksy.audio.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.Map;
  14. import java.util.Set;
  15. import java.util.concurrent.ConcurrentHashMap;
  16. import java.time.Clock;
  17. import java.util.Arrays;
  18. @Component
  19. public class DeviceOfflineCheckTask extends RefreshableOfflineCheckTask {
  20. private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
  21. public static ConcurrentHashMap<String, Date> deviceLastReceiveTimeMap = new ConcurrentHashMap<>();
  22. private final Set<String> offlineDeviceSet = ConcurrentHashMap.newKeySet();
  23. private final Set<String> onlineDeviceSet = ConcurrentHashMap.newKeySet();
  24. private final Object[] deviceLocks = new Object[128];
  25. private Clock clock = Clock.systemUTC();
  26. public DeviceOfflineCheckTask() {
  27. super(1560);
  28. Arrays.setAll(deviceLocks, i -> new Object());
  29. }
  30. @Autowired
  31. private RestTemplate restTemplate;
  32. @Autowired
  33. private CollectionLastReceiptService lastReceiptService;
  34. @Override
  35. public void checkDeviceOffline() {
  36. int timeoutMinutes = effectiveOfflineTimeoutMinutes();
  37. logger.info("离线巡检开始: collector=audio, timeoutMinutes={}, memoryDevices={}",
  38. timeoutMinutes, deviceLastReceiveTimeMap.size());
  39. if (lastReceiptService != null) {
  40. lastReceiptService.restore("audio", deviceLastReceiveTimeMap, offlineDeviceSet);
  41. }
  42. Date now = new Date(clock.millis());
  43. long timeoutMs = (long) timeoutMinutes * 60 * 1000;
  44. for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
  45. synchronized (deviceLock(entry.getKey())) {
  46. // 与在线恢复串行,且重新读取时间,避免旧快照把刚收到上报的设备置离线。
  47. Date latest = deviceLastReceiveTimeMap.get(entry.getKey());
  48. if (latest == null || now.getTime() - latest.getTime() <= timeoutMs) continue;
  49. if (offlineDeviceSet.add(entry.getKey())) {
  50. if (!updateDeviceOnlineStatus(entry.getKey(), 0)) {
  51. offlineDeviceSet.remove(entry.getKey());
  52. continue;
  53. }
  54. onlineDeviceSet.remove(entry.getKey());
  55. logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), timeoutMinutes);
  56. }
  57. }
  58. }
  59. }
  60. public void markDeviceOnline(String deviceCode) {
  61. if (deviceCode == null || deviceCode.trim().isEmpty()) return;
  62. synchronized (deviceLock(deviceCode)) {
  63. // 首次上报/服务重启后也需同步,不能只依赖本实例曾经标记过离线。
  64. if (!onlineDeviceSet.contains(deviceCode) && updateDeviceOnlineStatus(deviceCode, 1)) {
  65. onlineDeviceSet.add(deviceCode);
  66. offlineDeviceSet.remove(deviceCode);
  67. logger.info("设备 {} 已在线", deviceCode);
  68. }
  69. }
  70. }
  71. private Object deviceLock(String deviceCode) {
  72. return deviceLocks[(deviceCode.hashCode() & Integer.MAX_VALUE) % deviceLocks.length];
  73. }
  74. private boolean updateDeviceOnlineStatus(String deviceCode, int onlineStatus) {
  75. try {
  76. Map<String, Object> params = Map.of("deviceCode", deviceCode, "onlineStatus", onlineStatus);
  77. HttpHeaders headers = new HttpHeaders();
  78. headers.setContentType(MediaType.APPLICATION_JSON);
  79. HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, headers);
  80. Map<?, ?> response = restTemplate.postForObject("http://zk-api-service/equipmentStatus/updateOnlineStatus", request, Map.class);
  81. if (response == null || !Boolean.TRUE.equals(response.get("success"))) {
  82. logger.warn("在线状态同步未成功,下次重试: deviceCode={}, onlineStatus={}", deviceCode, onlineStatus);
  83. return false;
  84. }
  85. return true;
  86. } catch (Exception e) {
  87. logger.error("更新设备在线状态失败: deviceCode={}, onlineStatus={}", deviceCode, onlineStatus, e);
  88. return false;
  89. }
  90. }
  91. }