|
|
@@ -1,8 +1,11 @@
|
|
|
package com.zksy.api.scheduling;
|
|
|
|
|
|
+import com.zksy.api.service.CollectionLastReceiptService;
|
|
|
+import com.zksy.api.service.EquipmentStatusApiService;
|
|
|
import org.slf4j.Logger;
|
|
|
import org.slf4j.LoggerFactory;
|
|
|
import org.springframework.beans.factory.DisposableBean;
|
|
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
|
|
|
import org.springframework.context.ApplicationContext;
|
|
|
import org.springframework.context.ApplicationContextAware;
|
|
|
@@ -13,21 +16,41 @@ import org.springframework.context.event.ContextRefreshedEvent;
|
|
|
import org.springframework.core.env.Environment;
|
|
|
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
|
|
|
|
|
+import java.util.Arrays;
|
|
|
+import java.util.Date;
|
|
|
+import java.util.Map;
|
|
|
import java.util.Objects;
|
|
|
+import java.util.Set;
|
|
|
+import java.util.concurrent.ConcurrentHashMap;
|
|
|
import java.util.concurrent.ScheduledFuture;
|
|
|
|
|
|
/**
|
|
|
- * Nacos刷新后重新读取离线参数并重排巡检,不重建有设备状态缓存的任务bean。
|
|
|
+ * 采集服务设备离线巡检基类:统一调度、Nacos 参数刷新、在线/离线缓存与状态落库。
|
|
|
* 每个采集实例仅使用一条调度线程,刷新时不打断正在执行的巡检,也不会并发巡检。
|
|
|
*/
|
|
|
-public abstract class RefreshableOfflineCheckTask implements EnvironmentAware, ApplicationContextAware,
|
|
|
- ApplicationListener<ApplicationEvent>, DisposableBean {
|
|
|
+public abstract class RefreshableOfflineCheckTask implements EnvironmentAware, ApplicationContextAware, ApplicationListener<ApplicationEvent>, DisposableBean {
|
|
|
private static final Logger log = LoggerFactory.getLogger(RefreshableOfflineCheckTask.class);
|
|
|
private static final String TIMEOUT_KEY = "device.offline.timeout-minutes";
|
|
|
private static final String INTERVAL_KEY = "device.offline.check-interval-ms";
|
|
|
private static final long DEFAULT_INTERVAL_MS = 300000;
|
|
|
|
|
|
- /** 未显式配置时使用的服务默认值;音频通过构造器设为1560分钟。 */
|
|
|
+ /**
|
|
|
+ * 各采集实例共享的设备最后接收时间缓存,采集回调与巡检线程都会读写。
|
|
|
+ */
|
|
|
+ public static final 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];
|
|
|
+
|
|
|
+ @Autowired
|
|
|
+ private CollectionLastReceiptService lastReceiptService;
|
|
|
+ @Autowired
|
|
|
+ private EquipmentStatusApiService equipmentStatusApiService;
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 未显式配置时使用的服务默认值;音频通过构造器设为1560分钟。
|
|
|
+ */
|
|
|
protected int offlineTimeoutMinutes;
|
|
|
private final Object lifecycleLock = new Object();
|
|
|
private final PositiveSetting timeoutSetting;
|
|
|
@@ -40,26 +63,43 @@ public abstract class RefreshableOfflineCheckTask implements EnvironmentAware, A
|
|
|
private int scheduledTimeoutMinutes;
|
|
|
private boolean closed;
|
|
|
|
|
|
- protected RefreshableOfflineCheckTask() { this(30); }
|
|
|
+ protected RefreshableOfflineCheckTask() {
|
|
|
+ this(30);
|
|
|
+ }
|
|
|
|
|
|
protected RefreshableOfflineCheckTask(int defaultTimeoutMinutes) {
|
|
|
offlineTimeoutMinutes = defaultTimeoutMinutes;
|
|
|
timeoutSetting = new PositiveSetting(TIMEOUT_KEY, defaultTimeoutMinutes, Integer.MAX_VALUE);
|
|
|
+ Arrays.setAll(deviceLocks, i -> new Object());
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 采集器标识,用于日志与数据库在线名单恢复。
|
|
|
+ */
|
|
|
+ protected abstract String collector();
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void setEnvironment(Environment environment) {
|
|
|
+ this.environment = environment;
|
|
|
}
|
|
|
|
|
|
- @Override public void setEnvironment(Environment environment) { this.environment = environment; }
|
|
|
- @Override public void setApplicationContext(ApplicationContext context) { applicationContext = context; }
|
|
|
+ @Override
|
|
|
+ public void setApplicationContext(ApplicationContext context) {
|
|
|
+ applicationContext = context;
|
|
|
+ }
|
|
|
|
|
|
- /** 每轮读取当前Environment,避免普通@Value字段在Nacos刷新后仍保留启动值。 */
|
|
|
+ /**
|
|
|
+ * 每轮读取当前Environment,避免普通@Value字段在Nacos刷新后仍保留启动值。
|
|
|
+ */
|
|
|
protected final int effectiveOfflineTimeoutMinutes() {
|
|
|
synchronized (lifecycleLock) {
|
|
|
return (int) timeoutSetting.read(environment, offlineTimeoutMinutes);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- @Override public final void onApplicationEvent(ApplicationEvent event) {
|
|
|
- if (event instanceof ContextRefreshedEvent
|
|
|
- && ((ContextRefreshedEvent) event).getApplicationContext() == applicationContext) {
|
|
|
+ @Override
|
|
|
+ public final void onApplicationEvent(ApplicationEvent event) {
|
|
|
+ if (event instanceof ContextRefreshedEvent && ((ContextRefreshedEvent) event).getApplicationContext() == applicationContext) {
|
|
|
configureSchedule(true);
|
|
|
} else if (event instanceof EnvironmentChangeEvent) {
|
|
|
EnvironmentChangeEvent changed = (EnvironmentChangeEvent) event;
|
|
|
@@ -88,14 +128,76 @@ public abstract class RefreshableOfflineCheckTask implements EnvironmentAware, A
|
|
|
scheduled = scheduler.scheduleAtFixedRate(this::checkDeviceOffline, interval);
|
|
|
scheduledTimeoutMinutes = timeout;
|
|
|
scheduledIntervalMs = interval;
|
|
|
- log.info("离线巡检配置生效: task={}, timeoutMinutes={}, checkIntervalMs={}",
|
|
|
- getClass().getName(), timeout, interval);
|
|
|
+ log.info("离线巡检配置生效: task={}, timeoutMinutes={}, checkIntervalMs={}", getClass().getName(), timeout, interval);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- public abstract void checkDeviceOffline();
|
|
|
+ /**
|
|
|
+ * 每轮巡检:按超时阈值把静默设备置为离线,状态更新失败则下轮重试。
|
|
|
+ */
|
|
|
+ public final void checkDeviceOffline() {
|
|
|
+ int timeoutMinutes = effectiveOfflineTimeoutMinutes();
|
|
|
+ log.info("离线巡检开始: collector={}, timeoutMinutes={}, memoryDevices={}", collector(), timeoutMinutes, deviceLastReceiveTimeMap.size());
|
|
|
+ if (lastReceiptService != null) {
|
|
|
+ lastReceiptService.restore(collector(), 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());
|
|
|
+ log.info("设备 {} 已离线(超过{}分钟未收到数据)", entry.getKey(), timeoutMinutes);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 标记设备在线(收到数据时调用)。
|
|
|
+ * 首次上报、服务重启或离线恢复均需同步;状态更新失败时保留下次上报的重试机会。
|
|
|
+ */
|
|
|
+ public final 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);
|
|
|
+ log.info("设备 {} 已在线", deviceCode);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private Object deviceLock(String deviceCode) {
|
|
|
+ return deviceLocks[(deviceCode.hashCode() & Integer.MAX_VALUE) % deviceLocks.length];
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 本地调用 zk-api-service 的设备状态服务,替代原 HTTP 同步。
|
|
|
+ */
|
|
|
+ private boolean updateDeviceOnlineStatus(String deviceCode, int onlineStatus) {
|
|
|
+ try {
|
|
|
+ boolean updated = equipmentStatusApiService.updateOnlineStatus(deviceCode, onlineStatus);
|
|
|
+ if (!updated) {
|
|
|
+ log.warn("在线状态同步未成功,下次重试: deviceCode={}, onlineStatus={}", deviceCode, onlineStatus);
|
|
|
+ }
|
|
|
+ return updated;
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error("更新设备在线状态失败: deviceCode={}, onlineStatus={}", deviceCode, onlineStatus, e);
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ }
|
|
|
|
|
|
- @Override public final void destroy() {
|
|
|
+ @Override
|
|
|
+ public final void destroy() {
|
|
|
ThreadPoolTaskScheduler previous;
|
|
|
synchronized (lifecycleLock) {
|
|
|
closed = true;
|
|
|
@@ -106,7 +208,9 @@ public abstract class RefreshableOfflineCheckTask implements EnvironmentAware, A
|
|
|
if (previous != null) previous.shutdown();
|
|
|
}
|
|
|
|
|
|
- /** 非法配置保留最近有效值,防止0/负数令全部设备离线或让定时任务终止。 */
|
|
|
+ /**
|
|
|
+ * 非法配置保留最近有效值,防止0/负数令全部设备离线或让定时任务终止。
|
|
|
+ */
|
|
|
private static final class PositiveSetting {
|
|
|
private final String key;
|
|
|
private final long max;
|
|
|
@@ -114,18 +218,24 @@ public abstract class RefreshableOfflineCheckTask implements EnvironmentAware, A
|
|
|
private String lastInvalid;
|
|
|
|
|
|
private PositiveSetting(String key, long initial, long max) {
|
|
|
- this.key = key; this.lastValid = initial; this.max = max;
|
|
|
+ this.key = key;
|
|
|
+ this.lastValid = initial;
|
|
|
+ this.max = max;
|
|
|
}
|
|
|
|
|
|
private long read(Environment environment, long fallback) {
|
|
|
String raw = environment == null ? null : environment.getProperty(key);
|
|
|
if (raw == null) {
|
|
|
- lastValid = fallback; lastInvalid = null; return fallback;
|
|
|
+ lastValid = fallback;
|
|
|
+ lastInvalid = null;
|
|
|
+ return fallback;
|
|
|
}
|
|
|
try {
|
|
|
long value = Long.parseLong(raw.trim());
|
|
|
if (value <= 0 || value > max) throw new NumberFormatException();
|
|
|
- lastValid = value; lastInvalid = null; return value;
|
|
|
+ lastValid = value;
|
|
|
+ lastInvalid = null;
|
|
|
+ return value;
|
|
|
} catch (NumberFormatException e) {
|
|
|
if (!Objects.equals(raw, lastInvalid)) {
|
|
|
log.warn("离线巡检参数必须为有效正整数,沿用最近有效值: key={}, effectiveValue={}", key, lastValid);
|