package com.threecloud.dataserviceyy.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.Date; /** * 同步时间工具类 * 管理设备上次同步时间的本地文件存储 */ public class SyncTimeUtil { private static final Logger logger = LoggerFactory.getLogger(SyncTimeUtil.class); /** * 从本地文件读取上次同步时间 * * @param basePath 基础路径 * @param deviceId 设备ID * @return 上次同步时间,不存在返回null */ public static Date readLastSyncTime(String basePath, String deviceId) { String markerPath = FilePathUtil.buildSyncMarkerPath(basePath, deviceId); File markerFile = new File(markerPath); if (!markerFile.exists()) { logger.debug("同步标记文件不存在: deviceId={}", deviceId); return null; } try { byte[] bytes = Files.readAllBytes(markerFile.toPath()); long millis = Long.parseLong(new String(bytes).trim()); Date syncTime = new Date(millis); logger.debug("读取到上次同步时间: deviceId={}, time={}", deviceId, syncTime); return syncTime; } catch (Exception e) { logger.warn("读取同步时间失败: deviceId={}, error={}", deviceId, e.getMessage()); return null; } } /** * 保存同步时间到本地文件 * * @param basePath 基础路径 * @param deviceId 设备ID * @param time 同步时间 */ public static void writeLastSyncTime(String basePath, String deviceId, Date time) { String markerDir = FilePathUtil.buildSyncMarkerDir(basePath); File dir = new File(markerDir); if (!dir.exists() && !dir.mkdirs() && !dir.exists()) { logger.warn("创建同步标记目录失败: {}", markerDir); return; } String markerPath = FilePathUtil.buildSyncMarkerPath(basePath, deviceId); File markerFile = new File(markerPath); Path tempFile = null; try { tempFile = Files.createTempFile(dir.toPath(), deviceId + ".", ".tmp"); Files.write(tempFile, String.valueOf(time.getTime()).getBytes("UTF-8")); try { Files.move(tempFile, markerFile.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } catch (java.nio.file.AtomicMoveNotSupportedException e) { Files.move(tempFile, markerFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } logger.debug("保存同步时间成功: deviceId={}, time={}", deviceId, time); } catch (Exception e) { logger.warn("保存同步时间失败: deviceId={}, error={}", deviceId, e.getMessage()); } finally { if (tempFile != null) { try { Files.deleteIfExists(tempFile); } catch (Exception ignored) { // 临时文件清理由下次目录清理兜底。 } } } } }