perf: 为 SiteSnapshotService.getActive 增加 Caffeine 本地缓存
- 缓存过期时间 10 分钟,最大 500 条 - publish 时主动刷新缓存,确保最新配置立即可用 - 避免 mediabot 每次请求都查数据库
This commit is contained in:
@@ -2,6 +2,8 @@ package com.par.core.service.impl;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import com.par.common.util.HmacUtil;
|
||||
import com.par.core.adapter.GroovyScriptEngine;
|
||||
import com.par.core.entity.RiskRule;
|
||||
@@ -19,6 +21,7 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
@@ -40,6 +43,12 @@ public class SiteSnapshotServiceImpl implements SiteSnapshotService {
|
||||
private final CachedStorageService storageService;
|
||||
private static final ObjectMapper om = new ObjectMapper();
|
||||
|
||||
/** 已发布快照本地缓存:key=siteId, value=SiteSnapshot */
|
||||
private final Cache<String, SiteSnapshot> activeSnapshotCache = Caffeine.newBuilder()
|
||||
.expireAfterWrite(Duration.ofMinutes(10))
|
||||
.maximumSize(500)
|
||||
.build();
|
||||
|
||||
@Override
|
||||
public Map<String, Object> buildSnapshot(String siteId) {
|
||||
Map<String, Object> snapshot = new LinkedHashMap<>();
|
||||
@@ -184,6 +193,9 @@ public class SiteSnapshotServiceImpl implements SiteSnapshotService {
|
||||
draft.setPublishedAt(LocalDateTime.now());
|
||||
snapshotMapper.updateById(draft);
|
||||
|
||||
// 刷新本地缓存
|
||||
activeSnapshotCache.put(siteId, draft);
|
||||
|
||||
// 上传到七牛云 CDN 作为灾备
|
||||
try {
|
||||
String bundleJson = toBundleJson(draft);
|
||||
@@ -205,7 +217,10 @@ public class SiteSnapshotServiceImpl implements SiteSnapshotService {
|
||||
|
||||
@Override
|
||||
public SiteSnapshot getActive(String siteId) {
|
||||
return snapshotMapper.selectLatestPublished(siteId);
|
||||
return activeSnapshotCache.get(siteId, key -> {
|
||||
log.debug("缓存未命中,查询数据库 siteId={}", siteId);
|
||||
return snapshotMapper.selectLatestPublished(siteId);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
Reference in New Issue
Block a user