#
Junjie
3 天以前 24772b6aed1f11ee416415a154e6fca415f4154e
src/main/java/com/zy/core/task/DeviceLogScheduler.java
@@ -36,10 +36,23 @@
    private String storageType;
    @Value("${deviceLogStorage.loggingPath}")
    private String loggingPath;
    @Value("${deviceLogStorage.expireDays}")
    private Integer expireDays;
    @Autowired
    private DeviceDataLogService deviceDataLogService;
    @Autowired
    private RedisUtil redisUtil;
    @Scheduled(cron = "0/3 * * * * ? ")
    public void delDeviceLog() {
        if ("mysql".equals(storageType)) {
            deviceDataLogService.clearLog(expireDays == null ? 1 : expireDays);
        }else if ("file".equals(storageType)) {
            clearFileLog(expireDays == null ? 1 : expireDays);
        }else {
            log.error("未定义的存储类型:{}", storageType);
        }
    }
    @Scheduled(cron = "0/3 * * * * ? ")
    public void execute() {
@@ -151,4 +164,32 @@
        return candidate;
    }
    private void clearFileLog(int days) {
        try {
            Path baseDir = Paths.get(loggingPath);
            if (!Files.exists(baseDir)) {
                return;
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            long cutoff = System.currentTimeMillis() - (long) days * 24 * 60 * 60 * 1000;
            List<Path> dirs = Files.list(baseDir).filter(Files::isDirectory).collect(Collectors.toList());
            for (Path dir : dirs) {
                String name = dir.getFileName().toString();
                if (name.length() == 8 && name.chars().allMatch(Character::isDigit)) {
                    Date d = sdf.parse(name);
                    if (d.getTime() < cutoff) {
                        List<Path> all = Files.walk(dir).sorted(Comparator.reverseOrder()).collect(Collectors.toList());
                        for (Path p : all) {
                            try {
                                Files.deleteIfExists(p);
                            } catch (Exception ignored) {}
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("设备日志文件清理失败", e);
        }
    }
}