fix: 添加缓存表定时清理任务,修复 cache_link_info 无限增长

- CacheManager 添加 cleanupExpiredCache() 方法删除过期缓存记录
- PostExecVerticle 注册每小时执行一次的定时清理任务
- 原实现只有读时惰性检查过期,过期记录永远不会被删除,长期运行后数据库持续膨胀
This commit is contained in:
yukaidi
2026-05-28 23:20:17 +08:00
parent 8745dc3567
commit 0b024a849a
2 changed files with 37 additions and 2 deletions

View File

@@ -46,7 +46,7 @@ public class PostExecVerticle extends AbstractVerticle {
return;
}
LOGGER.info("PostExecVerticle 开始执行...");
if (appRunImplementations != null && !appRunImplementations.isEmpty()) {
appRunImplementations.forEach(appRun -> {
try {
@@ -61,7 +61,17 @@ public class PostExecVerticle extends AbstractVerticle {
} else {
LOGGER.info("未找到 AppRun 接口的实现类");
}
// 注册定时清理过期缓存任务(每小时执行一次)
vertx.setPeriodic(3600_000, 3600_000, id -> {
try {
cn.qaiu.lz.common.cache.CacheManager cacheManager = new cn.qaiu.lz.common.cache.CacheManager();
cacheManager.cleanupExpiredCache();
} catch (Exception e) {
LOGGER.debug("定时清理缓存任务跳过(数据库可能未就绪)", e);
}
});
LOGGER.info("PostExecVerticle 执行完成");
startPromise.complete();
}

View File

@@ -200,6 +200,31 @@ public class CacheManager {
return promise.future();
}
/**
* 清理过期缓存记录,防止数据库无限增长
* @return 删除的行数
*/
public Future<Integer> cleanupExpiredCache() {
String sql = "DELETE FROM cache_link_info WHERE expiration > 0 AND expiration < #{now}";
Map<String, Object> params = new HashMap<>();
params.put("now", System.currentTimeMillis());
Promise<Integer> promise = Promise.promise();
SqlTemplate.forUpdate(jdbcPool, sql)
.execute(params)
.onSuccess(res -> {
int deleted = res.rowCount();
if (deleted > 0) {
LOGGER.info("清理过期缓存记录 {} 条", deleted);
}
promise.complete(deleted);
})
.onFailure(e -> {
LOGGER.error("清理过期缓存失败", e);
promise.fail(e);
});
return promise.future();
}
public Future<Map<String, Integer>> getShareKeyTotal(String shareKey) {
String sql = """
SELECT `share_key`, SUM(cache_hit_total) AS hit_total, SUM(api_parser_total) AS parser_total