1919import org.springframework.stereotype.Service;
2020import org.slf4j.Logger;
2121import org.slf4j.LoggerFactory;
22+
2223import java.time.LocalDateTime;
2324import java.time.format.DateTimeFormatter;
2425import java.util.*;
2526import java.util.concurrent.ConcurrentHashMap;
2627import java.util.concurrent.atomic.AtomicInteger;
28+
2729@Service
2830public class DatabaseCleanupService {
2931
3032 private static final Logger logger = LoggerFactory.getLogger(DatabaseCleanupService.class);
31- private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
33+ private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
3234
3335 @Autowired
3436 private JdbcTemplate jdbcTemplate;
3537
3638 @Autowired
3739 private CleanupProperties cleanupProperties;
38- // 执行统计
40+
3941 private final Map<String, ExecutionStats> executionStats = new ConcurrentHashMap<>();
42+
4043 private final AtomicInteger totalExecutions = new AtomicInteger(0);
4144
4245 // 默认白名单表(如果配置文件未设置)
4346 private static final List<String> DEFAULT_TABLES = Arrays.asList(
44- "t_resource", "t_resource_group", "r_resource_group_resource", "t_app_extension",
45- "t_block", "t_block_carriers_relation", "t_block_group", "t_block_history",
46- "r_material_block", "r_material_history_block", "r_block_group_block", "t_datasource",
47- "t_i18n_entry", "t_model", "t_page", "t_page_history", "t_page_template"
47+ "t_resource", "t_resource_group", "r_resource_group_resource", "t_app_extension",
48+ "t_block", "t_block_carriers_relation", "t_block_group", "t_block_history",
49+ "r_material_block", "r_material_history_block", "r_block_group_block", "t_datasource",
50+ "t_i18n_entry", "t_model", "t_page", "t_page_history", "t_page_template"
4851 );
4952
5053 /**
@@ -53,32 +56,32 @@ public class DatabaseCleanupService {
5356 @Scheduled(cron = "${cleanup.cron-expression:0 0 0 * * ?}")
5457 public void autoCleanupAtMidnight() {
5558 if (!cleanupProperties.isEnabled()) {
56- logger.info("⏸️ 清空任务已禁用,跳过执行 ");
59+ logger.info("⏸️ Clearing tasks is disabled, skipping execution ");
5760 return;
5861 }
5962
6063 String executionId = UUID.randomUUID().toString().substring(0, 8);
61- String startTime = LocalDateTime.now().format(formatter );
64+ String startTime = LocalDateTime.now().format(FORMATTER );
6265
63- logger.info("🎯 ======= 开始执行数据库清空任务 [{}] =======", executionId);
64- logger.info("⏰ 执行时间 : {}", startTime);
65- logger.info("📋 目标表 : {}", getWhitelistTables());
66+ logger.info("======= Start executing the database clearing task [{}] =======", executionId);
67+ logger.info("⏰ Time : {}", startTime);
68+ logger.info("📋 Tables : {}", getWhitelistTables());
6669
6770 ExecutionStats stats = new ExecutionStats(executionId, startTime);
6871 executionStats.put(executionId, stats);
6972 totalExecutions.incrementAndGet();
7073
7174 int successCount = 0;
7275 int failedCount = 0;
73- long totalRowsCleaned = 0 ;
76+ long totalRowsCleaned = 0L ;
7477
7578 for (String tableName : getWhitelistTables()) {
7679 try {
7780 validateTableName(tableName);
7881
7982 if (!tableExists(tableName)) {
80- logger.warn("⚠️ 表 {} 不存在,跳过 ", tableName);
81- stats.recordSkipped(tableName, "表不存在 ");
83+ logger.warn("⚠️ Table {} does not exist, skip ", tableName);
84+ stats.recordSkipped(tableName, "Table does not exist ");
8285 continue;
8386 }
8487
@@ -87,35 +90,35 @@ public void autoCleanupAtMidnight() {
8790
8891 if (cleanupProperties.isUseTruncate()) {
8992 truncateTable(tableName);
90- rowsCleaned = beforeCount; // TRUNCATE会清空所有数据
93+ rowsCleaned = beforeCount;
9194 } else {
9295 rowsCleaned = clearTableData(tableName);
9396 }
9497
9598 totalRowsCleaned += rowsCleaned;
9699 successCount++;
97100
98- logger.info("✅ 表 {} 清空完成: 删除 {} 条记录 ", tableName, rowsCleaned);
101+ logger.info("✅ Table {} cleared: {} records deleted ", tableName, rowsCleaned);
99102 stats.recordSuccess(tableName, rowsCleaned);
100103
101104 } catch (Exception e) {
102105 failedCount++;
103- logger.error("❌ 表 {} 清空失败 : {}", tableName, e.getMessage(), e);
106+ logger.error("❌ Failed to clear table {} : {}", tableName, e.getMessage(), e);
104107 stats.recordFailure(tableName, e.getMessage());
105108 }
106109 }
107110
108- String endTime = LocalDateTime.now().format(formatter );
111+ String endTime = LocalDateTime.now().format(FORMATTER );
109112 stats.setEndTime(endTime);
110113 stats.setTotalRowsCleaned(totalRowsCleaned);
111114
112- logger.info("📊 ======= 任务完成统计 [{}] =======", executionId);
113- logger.info("✅ 成功表数 : {}", successCount);
114- logger.info("❌ 失败表数 : {}", failedCount);
115- logger.info("📈 总共删除记录 : {}", totalRowsCleaned);
116- logger.info("⏰ 耗时 : {} 秒 ", stats.getDurationSeconds());
117- logger.info("🕐 开始 : {}, 结束 : {}", startTime, endTime);
118- logger.info("🎉 ======= 任务执行完成 =======\n");
115+ logger.info("📊 ======= Task Completion Statistics [{}] =======", executionId);
116+ logger.info("✅ Successful table count : {}", successCount);
117+ logger.info("❌ Failure count : {}", failedCount);
118+ logger.info("📈 Total deleted records : {}", totalRowsCleaned);
119+ logger.info("⏰ Time-consuming : {} second ", stats.getDurationSeconds());
120+ logger.info("🕐 Start : {}, End : {}", startTime, endTime);
121+ logger.info("🎉 ======= Task execution completed =======\n");
119122 }
120123
121124 /**
@@ -127,10 +130,10 @@ public void sendCleanupWarning() {
127130 return;
128131 }
129132
130- logger.warn("⚠️ ⚠️ ⚠️ 重要通知:5分钟后将自动清空数据库表 !");
131- logger.warn("📋 目标表 : {}", getWhitelistTables());
132- logger.warn("⏰ 执行时间 : 00:00:00");
133- logger.warn("💡 如需取消,请修改配置 : cleanup.enabled=false");
133+ logger.warn("⚠️ ⚠️ ⚠️ Important Notice: The database table will be automatically cleared in 5 minutes !");
134+ logger.warn("📋 Target table : {}", getWhitelistTables());
135+ logger.warn("⏰ Execution Time : 00:00:00");
136+ logger.warn("💡 If you need to cancel, please change the settings : cleanup.enabled=false");
134137 logger.warn("==========================================");
135138 }
136139
@@ -139,12 +142,13 @@ public void sendCleanupWarning() {
139142 */
140143 @PostConstruct
141144 public void init() {
142- logger.info("🚀 数据库自动清空服务初始化完成 ");
143- logger.info("📋 配置表 : {}", getWhitelistTables());
144- logger.info("⏰ 执行时间 : {}", cleanupProperties.getCronExpression());
145- logger.info("🔧 使用模式 : {}", cleanupProperties.isUseTruncate() ? "TRUNCATE" : "DELETE");
146- logger.info("✅ 服务状态 : {}", cleanupProperties.isEnabled() ? "已启用 " : "已禁用 ");
145+ logger.info("🚀 Database auto-clear service initialization completed ");
146+ logger.info("📋 Configuration table : {}", getWhitelistTables());
147+ logger.info("⏰ Execution time : {}", cleanupProperties.getCronExpression());
148+ logger.info("🔧 Mode in use : {}", cleanupProperties.isUseTruncate() ? "TRUNCATE" : "DELETE");
149+ logger.info("✅ Service status : {}", cleanupProperties.isEnabled() ? "Enabled " : "Disabled ");
147150 logger.info("==========================================");
151+
148152 }
149153
150154 /**
@@ -184,7 +188,7 @@ public boolean tableExists(String tableName) {
184188 Integer count = jdbcTemplate.queryForObject(sql, Integer.class, tableName.toUpperCase());
185189 return count != null && count > 0;
186190 } catch (Exception e) {
187- logger.warn("检查表存在失败 : {}", e.getMessage());
191+ logger.warn("The checklist has failed : {}", e.getMessage());
188192 return false;
189193 }
190194 }
@@ -209,10 +213,10 @@ public long getTableRecordCount(String tableName) {
209213 */
210214 private void validateTableName(String tableName) {
211215 if (tableName == null || tableName.trim().isEmpty()) {
212- throw new IllegalArgumentException("表名不能为空 ");
216+ throw new IllegalArgumentException("Table name cannot be empty ");
213217 }
214218 if (!tableName.matches("^[a-zA-Z_][a-zA-Z0-9_]*$")) {
215- throw new IllegalArgumentException("无效的表名格式 : " + tableName);
219+ throw new IllegalArgumentException("Invalid table name format : " + tableName);
216220 }
217221 }
218222
@@ -255,18 +259,38 @@ public void recordSkipped(String tableName, String reason) {
255259 }
256260
257261 // Getters and setters
258- public String getExecutionId() { return executionId; }
259- public String getStartTime() { return startTime; }
260- public String getEndTime() { return endTime; }
261- public void setEndTime(String endTime) { this.endTime = endTime; }
262- public long getTotalRowsCleaned() { return totalRowsCleaned; }
263- public void setTotalRowsCleaned(long totalRowsCleaned) { this.totalRowsCleaned = totalRowsCleaned; }
264- public Map<String, TableResult> getTableResults() { return tableResults; }
262+ public String getExecutionId() {
263+ return executionId;
264+ }
265+
266+ public String getStartTime() {
267+ return startTime;
268+ }
269+
270+ public String getEndTime() {
271+ return endTime;
272+ }
273+
274+ public void setEndTime(String endTime) {
275+ this.endTime = endTime;
276+ }
277+
278+ public long getTotalRowsCleaned() {
279+ return totalRowsCleaned;
280+ }
281+
282+ public void setTotalRowsCleaned(long totalRowsCleaned) {
283+ this.totalRowsCleaned = totalRowsCleaned;
284+ }
285+
286+ public Map<String, TableResult> getTableResults() {
287+ return tableResults;
288+ }
265289
266290 public long getDurationSeconds() {
267291 if (startTime != null && endTime != null) {
268- LocalDateTime start = LocalDateTime.parse(startTime, formatter );
269- LocalDateTime end = LocalDateTime.parse(endTime, formatter );
292+ LocalDateTime start = LocalDateTime.parse(startTime, FORMATTER );
293+ LocalDateTime end = LocalDateTime.parse(endTime, FORMATTER );
270294 return java.time.Duration.between(start, end).getSeconds();
271295 }
272296 return 0;
@@ -288,8 +312,16 @@ public TableResult(String status, long rowsCleaned, String message) {
288312 }
289313
290314 // Getters
291- public String getStatus() { return status; }
292- public long getRowsCleaned() { return rowsCleaned; }
293- public String getMessage() { return message; }
315+ public String getStatus() {
316+ return status;
317+ }
318+
319+ public long getRowsCleaned() {
320+ return rowsCleaned;
321+ }
322+
323+ public String getMessage() {
324+ return message;
325+ }
294326 }
295327}
0 commit comments