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