| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- 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<String, Date> deviceLastReceiveTimeMap = new ConcurrentHashMap<>();
- private final Set<String> offlineDeviceSet = ConcurrentHashMap.newKeySet();
- /** 本实例已成功同步在线的设备;不能把尚未检测过离线当作已经在线。 */
- private final Set<String> 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<String, Date> 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<String, Object> params = Map.of("deviceCode", deviceCode, "onlineStatus", onlineStatus);
- HttpHeaders headers = new HttpHeaders();
- headers.setContentType(MediaType.APPLICATION_JSON);
- HttpEntity<Map<String, Object>> 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;
- }
- }
- }
|