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);
|
}
|
}
|
}
|