DeviceOfflineCheckTask.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package com.zksy.gas.utils;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.http.HttpEntity;
  7. import org.springframework.http.HttpHeaders;
  8. import org.springframework.http.MediaType;
  9. import org.springframework.scheduling.annotation.Scheduled;
  10. import org.springframework.stereotype.Component;
  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. @Component
  17. public class DeviceOfflineCheckTask {
  18. private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class);
  19. public static ConcurrentHashMap<String, Date> deviceLastReceiveTimeMap = new ConcurrentHashMap<>();
  20. private final Set<String> offlineDeviceSet = ConcurrentHashMap.newKeySet();
  21. @Autowired
  22. private RestTemplate restTemplate;
  23. @Value("${device.offline.timeout-minutes:30}")
  24. private int offlineTimeoutMinutes;
  25. @Scheduled(fixedRateString = "${device.offline.check-interval-ms:300000}")
  26. public void checkDeviceOffline() {
  27. Date now = new Date();
  28. long timeoutMs = (long) offlineTimeoutMinutes * 60 * 1000;
  29. for (Map.Entry<String, Date> entry : deviceLastReceiveTimeMap.entrySet()) {
  30. long diff = now.getTime() - entry.getValue().getTime();
  31. if (diff > timeoutMs) {
  32. if (offlineDeviceSet.add(entry.getKey())) {
  33. updateDeviceOnlineStatus(entry.getKey(), 0);
  34. logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), offlineTimeoutMinutes);
  35. }
  36. }
  37. }
  38. }
  39. public void markDeviceOnline(String deviceCode) {
  40. if (offlineDeviceSet.remove(deviceCode)) {
  41. updateDeviceOnlineStatus(deviceCode, 1);
  42. logger.info("设备 {} 恢复在线", deviceCode);
  43. }
  44. }
  45. private void updateDeviceOnlineStatus(String deviceCode, int onlineStatus) {
  46. try {
  47. Map<String, Object> params = Map.of("deviceCode", deviceCode, "onlineStatus", onlineStatus);
  48. HttpHeaders headers = new HttpHeaders();
  49. headers.setContentType(MediaType.APPLICATION_JSON);
  50. HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, headers);
  51. restTemplate.postForObject("http://zk-api-service/equipmentStatus/updateOnlineStatus", request, Map.class);
  52. } catch (Exception e) {
  53. logger.error("更新设备在线状态失败: deviceCode={}, onlineStatus={}", deviceCode, onlineStatus, e);
  54. }
  55. }
  56. }