cl
2026-04-17 f7e46d204be81fd2ebb9e5a90728e945700a2c23
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.vincent.rsf.httpaudit.service;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.vincent.rsf.httpaudit.entity.HttpAuditLog;
import com.vincent.rsf.httpaudit.mapper.HttpAuditLogMapper;
import com.vincent.rsf.httpaudit.props.HttpAuditProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
 
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
 
/**
 * 审计日志定期清理
 */
@Slf4j
public class HttpAuditCleanupService {
 
    private final HttpAuditLogMapper httpAuditLogMapper;
    private final HttpAuditProperties props;
 
    public HttpAuditCleanupService(HttpAuditLogMapper httpAuditLogMapper, HttpAuditProperties props) {
        this.httpAuditLogMapper = httpAuditLogMapper;
        this.props = props;
    }
 
    @Scheduled(cron = "${http-audit.cleanup-cron:0 30 2 * * ?}")
    public void cleanup() {
        if (!props.isCleanupEnabled()) {
            return;
        }
        int retentionDays = props.getCleanupRetentionDays();
        if (retentionDays <= 0) {
            log.warn("http-audit 清理已跳过,retentionDays 配置无效:{}", retentionDays);
            return;
        }
        try {
            LocalDateTime cutoff = LocalDateTime.now().minusDays(retentionDays);
            Date cutoffDate = Date.from(cutoff.atZone(ZoneId.systemDefault()).toInstant());
            int count = httpAuditLogMapper.delete(new LambdaQueryWrapper<HttpAuditLog>()
                    .lt(HttpAuditLog::getCreateTime, cutoffDate));
            if (count > 0) {
                log.info("http-audit 清理完成,删除 {} 条,保留天数 {}", count, retentionDays);
            }
        } catch (Exception e) {
            log.warn("http-audit 清理失败", e);
        }
    }
}