package com.zksy.telemetry.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import com.zksy.api.scheduling.RefreshableOfflineCheckTask; import org.springframework.stereotype.Component; import com.zksy.api.service.CollectionLastReceiptService; import org.springframework.web.client.RestTemplate; import java.util.Date; import java.util.Arrays; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @Component public class DeviceOfflineCheckTask extends RefreshableOfflineCheckTask { private static final Logger logger = LoggerFactory.getLogger(DeviceOfflineCheckTask.class); public static ConcurrentHashMap deviceLastReceiveTimeMap = new ConcurrentHashMap<>(); private final Set offlineDeviceSet = ConcurrentHashMap.newKeySet(); /** 本实例已成功同步在线的设备;不能把尚未检测过离线当作已经在线。 */ private final Set onlineDeviceSet = ConcurrentHashMap.newKeySet(); private final Object[] deviceLocks = new Object[128]; public DeviceOfflineCheckTask() { Arrays.setAll(deviceLocks, i -> new Object()); } @Autowired private RestTemplate restTemplate; @Autowired private CollectionLastReceiptService lastReceiptService; @Override 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(); long timeoutMs = (long) timeoutMinutes * 60 * 1000; for (Map.Entry entry : deviceLastReceiveTimeMap.entrySet()) { synchronized (deviceLock(entry.getKey())) { // 与在线更新串行,重新读取时间,避免用旧快照覆盖刚收到的上报。 Date latest = deviceLastReceiveTimeMap.get(entry.getKey()); if (latest == null || now.getTime() - latest.getTime() <= timeoutMs) continue; if (offlineDeviceSet.add(entry.getKey())) { if (!updateDeviceOnlineStatus(entry.getKey(), 0)) { offlineDeviceSet.remove(entry.getKey()); continue; } onlineDeviceSet.remove(entry.getKey()); logger.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), timeoutMinutes); } } } } public void markDeviceOnline(String deviceCode) { if (deviceCode == null || deviceCode.trim().isEmpty()) return; synchronized (deviceLock(deviceCode)) { // 仅在接口明确成功后缓存;新建默认离线的设备首次上报也会进入这里。 if (!onlineDeviceSet.contains(deviceCode) && updateDeviceOnlineStatus(deviceCode, 1)) { onlineDeviceSet.add(deviceCode); offlineDeviceSet.remove(deviceCode); logger.info("设备 {} 已在线", deviceCode); } } } private Object deviceLock(String deviceCode) { return deviceLocks[(deviceCode.hashCode() & Integer.MAX_VALUE) % deviceLocks.length]; } private boolean updateDeviceOnlineStatus(String deviceCode, int onlineStatus) { try { Map params = Map.of("deviceCode", deviceCode, "onlineStatus", onlineStatus); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity> request = new HttpEntity<>(params, headers); Map response = restTemplate.postForObject("http://zk-api-service/equipmentStatus/updateOnlineStatus", request, Map.class); if (response == null || !Boolean.TRUE.equals(response.get("success"))) { logger.warn("在线状态同步未成功,下次重试: deviceCode={}, onlineStatus={}", deviceCode, onlineStatus); return false; } return true; } catch (Exception e) { logger.error("更新设备在线状态失败: deviceCode={}, onlineStatus={}", deviceCode, onlineStatus, e); return false; } } }