perf: preview查询改为一条SQL(draft优先,无则published),独立preview缓存

This commit is contained in:
mediabot-pt
2026-07-07 11:39:42 +08:00
parent e15e242153
commit e839fe9bba
2 changed files with 22 additions and 7 deletions

View File

@@ -19,4 +19,8 @@ public interface SiteSnapshotMapper extends BaseMapper<SiteSnapshot> {
/** 查询站点最新的 published 快照 */
@Select("SELECT * FROM site_snapshots WHERE site_id = #{siteId} AND status = 'published' ORDER BY version DESC LIMIT 1")
SiteSnapshot selectLatestPublished(@Param("siteId") String siteId);
/** 查询站点最新快照:draft 优先,无 draft 则取 published */
@Select("SELECT * FROM site_snapshots WHERE site_id = #{siteId} AND status IN ('draft','published') ORDER BY CASE WHEN status = 'draft' THEN 0 ELSE 1 END, version DESC LIMIT 1")
SiteSnapshot selectLatestWithDraft(@Param("siteId") String siteId);
}

View File

@@ -55,6 +55,12 @@ public class SiteSnapshotServiceImpl implements SiteSnapshotService {
.maximumSize(500)
.build();
/** preview 快照 JSON 缓存:draft 优先 fallback published */
private final Cache<String, String> previewJsonCache = Caffeine.newBuilder()
.expireAfterWrite(Duration.ofMinutes(5))
.maximumSize(500)
.build();
@Override
public Map<String, Object> buildSnapshot(String siteId) {
Map<String, Object> snapshot = new LinkedHashMap<>();
@@ -243,8 +249,9 @@ public class SiteSnapshotServiceImpl implements SiteSnapshotService {
// 序列化并刷新缓存
String bundleJson = toBundleJson(draft);
bundleJsonCache.put(siteId, bundleJson);
// 发布后 draft 缓存已过时,清除
// 发布后 draft/preview 缓存已过时
draftJsonCache.invalidate(siteId);
previewJsonCache.invalidate(siteId);
// 上传到七牛云 CDN 作为灾备(复用已序列化的 JSON)
try {
@@ -297,12 +304,16 @@ public class SiteSnapshotServiceImpl implements SiteSnapshotService {
@Override
public String getPreviewBundleJson(String siteId) {
// 先查 draft,有则返回;无则 fallback 到 published
String draftJson = getDraftBundleJson(siteId);
if (draftJson != null && !draftJson.isEmpty()) {
return draftJson;
}
return getActiveBundleJson(siteId);
// draft 优先,无 draft 则取 published — 一次查询
return previewJsonCache.get(siteId, key -> {
SiteSnapshot snapshot = snapshotMapper.selectLatestWithDraft(key);
if (snapshot == null) {
log.debug("站点 {} 无任何快照", key);
return "";
}
log.debug("预览缓存未命中 siteId={} status={}", key, snapshot.getStatus());
return toBundleJson(snapshot);
});
}
@Override