forked from opentiny/tiny-engine-backend-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseCleanupService.java
More file actions
295 lines (254 loc) · 11.1 KB
/
DatabaseCleanupService.java
File metadata and controls
295 lines (254 loc) · 11.1 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
/**
* Copyright (c) 2023 - present TinyEngine Authors.
* Copyright (c) 2023 - present Huawei Cloud Computing Technologies Co., Ltd.
*
* Use of this source code is governed by an MIT-style license.
*
* THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL,
* BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR
* A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS.
*
*/
package com.tinyengine.it.task;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
@Service
public class DatabaseCleanupService {
private static final Logger logger = LoggerFactory.getLogger(DatabaseCleanupService.class);
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private CleanupProperties cleanupProperties;
// 执行统计
private final Map<String, ExecutionStats> executionStats = new ConcurrentHashMap<>();
private final AtomicInteger totalExecutions = new AtomicInteger(0);
// 默认白名单表(如果配置文件未设置)
private static final List<String> DEFAULT_TABLES = Arrays.asList(
"t_resource", "t_resource_group", "r_resource_group_resource", "t_app_extension",
"t_block", "t_block_carriers_relation", "t_block_group", "t_block_history",
"r_material_block", "r_material_history_block", "r_block_group_block", "t_datasource",
"t_i18n_entry", "t_model", "t_page", "t_page_history", "t_page_template"
);
/**
* 每天24:00自动执行清空操作
*/
@Scheduled(cron = "${cleanup.cron-expression:0 0 0 * * ?}")
public void autoCleanupAtMidnight() {
if (!cleanupProperties.isEnabled()) {
logger.info("⏸️ 清空任务已禁用,跳过执行");
return;
}
String executionId = UUID.randomUUID().toString().substring(0, 8);
String startTime = LocalDateTime.now().format(formatter);
logger.info("🎯 ======= 开始执行数据库清空任务 [{}] =======", executionId);
logger.info("⏰ 执行时间: {}", startTime);
logger.info("📋 目标表: {}", getWhitelistTables());
ExecutionStats stats = new ExecutionStats(executionId, startTime);
executionStats.put(executionId, stats);
totalExecutions.incrementAndGet();
int successCount = 0;
int failedCount = 0;
long totalRowsCleaned = 0;
for (String tableName : getWhitelistTables()) {
try {
validateTableName(tableName);
if (!tableExists(tableName)) {
logger.warn("⚠️ 表 {} 不存在,跳过", tableName);
stats.recordSkipped(tableName, "表不存在");
continue;
}
long beforeCount = getTableRecordCount(tableName);
long rowsCleaned;
if (cleanupProperties.isUseTruncate()) {
truncateTable(tableName);
rowsCleaned = beforeCount; // TRUNCATE会清空所有数据
} else {
rowsCleaned = clearTableData(tableName);
}
totalRowsCleaned += rowsCleaned;
successCount++;
logger.info("✅ 表 {} 清空完成: 删除 {} 条记录", tableName, rowsCleaned);
stats.recordSuccess(tableName, rowsCleaned);
} catch (Exception e) {
failedCount++;
logger.error("❌ 表 {} 清空失败: {}", tableName, e.getMessage(), e);
stats.recordFailure(tableName, e.getMessage());
}
}
String endTime = LocalDateTime.now().format(formatter);
stats.setEndTime(endTime);
stats.setTotalRowsCleaned(totalRowsCleaned);
logger.info("📊 ======= 任务完成统计 [{}] =======", executionId);
logger.info("✅ 成功表数: {}", successCount);
logger.info("❌ 失败表数: {}", failedCount);
logger.info("📈 总共删除记录: {}", totalRowsCleaned);
logger.info("⏰ 耗时: {} 秒", stats.getDurationSeconds());
logger.info("🕐 开始: {}, 结束: {}", startTime, endTime);
logger.info("🎉 ======= 任务执行完成 =======\n");
}
/**
* 每天23:55发送预警通知
*/
@Scheduled(cron = "0 55 23 * * ?")
public void sendCleanupWarning() {
if (!cleanupProperties.isEnabled() || !cleanupProperties.isSendWarning()) {
return;
}
logger.warn("⚠️ ⚠️ ⚠️ 重要通知:5分钟后将自动清空数据库表!");
logger.warn("📋 目标表: {}", getWhitelistTables());
logger.warn("⏰ 执行时间: 00:00:00");
logger.warn("💡 如需取消,请修改配置: cleanup.enabled=false");
logger.warn("==========================================");
}
/**
* 应用启动时初始化
*/
@PostConstruct
public void init() {
logger.info("🚀 数据库自动清空服务初始化完成");
logger.info("📋 配置表: {}", getWhitelistTables());
logger.info("⏰ 执行时间: {}", cleanupProperties.getCronExpression());
logger.info("🔧 使用模式: {}", cleanupProperties.isUseTruncate() ? "TRUNCATE" : "DELETE");
logger.info("✅ 服务状态: {}", cleanupProperties.isEnabled() ? "已启用" : "已禁用");
logger.info("==========================================");
}
/**
* 获取白名单表列表
*/
public List<String> getWhitelistTables() {
List<String> tables = cleanupProperties.getWhitelistTables();
return tables != null && !tables.isEmpty() ? tables : DEFAULT_TABLES;
}
/**
* 清空表数据(DELETE方式)
*/
private long clearTableData(String tableName) {
validateTableName(tableName);
String sql = "DELETE FROM " + tableName;
int affectedRows = jdbcTemplate.update(sql);
return affectedRows;
}
/**
* 清空表数据(TRUNCATE方式)
*/
private void truncateTable(String tableName) {
validateTableName(tableName);
String sql = "TRUNCATE TABLE " + tableName;
jdbcTemplate.execute(sql);
}
/**
* 检查表是否存在
*/
public boolean tableExists(String tableName) {
try {
String sql = "SELECT COUNT(*) FROM information_schema.tables " +
"WHERE table_schema = DATABASE() AND table_name = ?";
Integer count = jdbcTemplate.queryForObject(sql, Integer.class, tableName.toUpperCase());
return count != null && count > 0;
} catch (Exception e) {
logger.warn("检查表存在失败: {}", e.getMessage());
return false;
}
}
/**
* 获取表记录数量
*/
public long getTableRecordCount(String tableName) {
try {
validateTableName(tableName);
String sql = "SELECT COUNT(*) FROM " + tableName;
Long count = jdbcTemplate.queryForObject(sql, Long.class);
return count != null ? count : 0;
} catch (Exception e) {
logger.error("获取表记录数失败: {}", e.getMessage());
return -1;
}
}
/**
* 验证表名安全性
*/
private void validateTableName(String tableName) {
if (tableName == null || tableName.trim().isEmpty()) {
throw new IllegalArgumentException("表名不能为空");
}
if (!tableName.matches("^[a-zA-Z_][a-zA-Z0-9_]*$")) {
throw new IllegalArgumentException("无效的表名格式: " + tableName);
}
}
/**
* 获取执行统计
*/
public Map<String, ExecutionStats> getExecutionStats() {
return new LinkedHashMap<>(executionStats);
}
public int getTotalExecutions() {
return totalExecutions.get();
}
/**
* 执行统计内部类
*/
public static class ExecutionStats {
private final String executionId;
private final String startTime;
private String endTime;
private long totalRowsCleaned;
private final Map<String, TableResult> tableResults = new LinkedHashMap<>();
public ExecutionStats(String executionId, String startTime) {
this.executionId = executionId;
this.startTime = startTime;
}
public void recordSuccess(String tableName, long rowsCleaned) {
tableResults.put(tableName, new TableResult("SUCCESS", rowsCleaned, null));
}
public void recordFailure(String tableName, String errorMessage) {
tableResults.put(tableName, new TableResult("FAILED", 0, errorMessage));
}
public void recordSkipped(String tableName, String reason) {
tableResults.put(tableName, new TableResult("SKIPPED", 0, reason));
}
// Getters and setters
public String getExecutionId() { return executionId; }
public String getStartTime() { return startTime; }
public String getEndTime() { return endTime; }
public void setEndTime(String endTime) { this.endTime = endTime; }
public long getTotalRowsCleaned() { return totalRowsCleaned; }
public void setTotalRowsCleaned(long totalRowsCleaned) { this.totalRowsCleaned = totalRowsCleaned; }
public Map<String, TableResult> getTableResults() { return tableResults; }
public long getDurationSeconds() {
if (startTime != null && endTime != null) {
LocalDateTime start = LocalDateTime.parse(startTime, formatter);
LocalDateTime end = LocalDateTime.parse(endTime, formatter);
return java.time.Duration.between(start, end).getSeconds();
}
return 0;
}
}
/**
* 表结果内部类
*/
public static class TableResult {
private final String status;
private final long rowsCleaned;
private final String message;
public TableResult(String status, long rowsCleaned, String message) {
this.status = status;
this.rowsCleaned = rowsCleaned;
this.message = message;
}
// Getters
public String getStatus() { return status; }
public long getRowsCleaned() { return rowsCleaned; }
public String getMessage() { return message; }
}
}