增加商品多规格探测缓存

This commit is contained in:
Christ committed 2026-08-15 16:08:37 +08:00
1 parent 8dbe2d6616
commit 6bc29829ba
4 files changed
+106 -1

No files matched your search

+66 -1
View File
@@ -763,6 +763,64 @@ func (s *Server) syncSyncedItems(ctx context.Context, cookieID string, items []m
// itemSpecProbeConcurrency 限制商品多规格远端探测的并发数,避免同步洪峰压垮平台接口。
const itemSpecProbeConcurrency = 4
// itemSpecCacheTTL 定义商品多规格探测结果的短期缓存时长。
const itemSpecCacheTTL = 10 * time.Minute
// itemSpecCacheEntry 保存商品多规格结果及其过期时间。
type itemSpecCacheEntry struct {
// isMultiSpec 表示商品是否包含多规格。
isMultiSpec bool
// expiresAt 表示该缓存项失效的时间。
expiresAt time.Time
}
// itemSpecCacheKey 生成账号与商品组合的缓存键,避免不同账号同商品 ID 相互污染。
func itemSpecCacheKey(cookieID, itemID string) string {
return cookieID + "\x00" + itemID
}
// cachedItemSpec 读取未过期的商品多规格缓存。
func (s *Server) cachedItemSpec(cookieID, itemID string) (bool, bool) {
if s == nil {
return false, false
}
s.itemSpecCacheMu.Lock()
defer s.itemSpecCacheMu.Unlock()
// key 表示账号与商品组合的缓存键。
key := itemSpecCacheKey(cookieID, itemID)
// entry、exists 保存缓存项及其存在状态。
entry, exists := s.itemSpecCache[key]
if !exists {
return false, false
}
if time.Now().After(entry.expiresAt) {
delete(s.itemSpecCache, key)
return false, false
}
return entry.isMultiSpec, true
}
// cacheItemSpec 写入商品多规格结果并清理已过期缓存项。
func (s *Server) cacheItemSpec(cookieID, itemID string, isMultiSpec bool) {
if s == nil || itemID == "" {
return
}
s.itemSpecCacheMu.Lock()
defer s.itemSpecCacheMu.Unlock()
if s.itemSpecCache == nil {
s.itemSpecCache = make(map[string]itemSpecCacheEntry)
}
// now 表示本次写入缓存的时间基准。
now := time.Now()
// key、entry 分别表示缓存键及其缓存项。
for key, entry := range s.itemSpecCache {
if now.After(entry.expiresAt) {
delete(s.itemSpecCache, key)
}
}
s.itemSpecCache[itemSpecCacheKey(cookieID, itemID)] = itemSpecCacheEntry{isMultiSpec: isMultiSpec, expiresAt: now.Add(itemSpecCacheTTL)}
}
// enrichSyncedItemMultiSpec 批量读取本地标记并受限并发探测剩余商品的多规格状态。
func (s *Server) enrichSyncedItemMultiSpec(ctx context.Context, client mtop.Client, cookies, cookieID string, items []mtop.ItemListItem) error {
// fetcher、ok 保存fetcher、ok,供当前处理流程使用
@@ -784,10 +842,16 @@ func (s *Server) enrichSyncedItemMultiSpec(ctx context.Context, client mtop.Clie
// candidates 保存需要访问远端接口的商品下标。
candidates := make([]int, 0, len(items))
// index 表示当前商品在同步列表中的下标。
// index 表示当前商品在同步列表中的下标。
for index := range items {
if items[index].IsMultiSpec || localFlags[items[index].ID] {
items[index].IsMultiSpec = true
s.cacheItemSpec(cookieID, items[index].ID, true)
continue
}
// cachedValue、cached 表示当前商品是否命中短期探测缓存。
cachedValue, cached := s.cachedItemSpec(cookieID, items[index].ID)
if cached {
items[index].IsMultiSpec = cachedValue
continue
}
candidates = append(candidates, index)
@@ -837,6 +901,7 @@ func (s *Server) enrichSyncedItemMultiSpec(ctx context.Context, client mtop.Clie
}
return
}
s.cacheItemSpec(cookieID, items[index].ID, isMultiSpec)
items[index].IsMultiSpec = isMultiSpec
}(index)
}
+34
View File
@@ -641,12 +641,15 @@ func TestEnrichSyncedItemMultiSpecLimitsProbeConcurrency(t *testing.T) {
var stateMu sync.Mutex
// active、maxActive 保存当前及观测到的最大远端探测并发数。
active, maxActive := 0, 0
// probeCalls 统计测试客户端收到的商品详情探测请求数。
probeCalls := 0
// client 是带并发计数的商品详情测试客户端。
client := withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
if !strings.Contains(req.URL.String(), "mtop.taobao.idle.pc.detail") {
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{}`)), Request: req}, nil
}
stateMu.Lock()
probeCalls++
active++
if active > maxActive {
maxActive = active
@@ -678,6 +681,19 @@ func TestEnrichSyncedItemMultiSpecLimitsProbeConcurrency(t *testing.T) {
t.Fatalf("item %d was not marked multi spec", index)
}
}
// cachedItems 保存第二次调用使用的商品列表,验证命中跨请求缓存。
cachedItems := make([]mtop.ItemListItem, 8)
// index 表示缓存测试商品下标。
for index := range cachedItems {
cachedItems[index].ID = fmt.Sprintf("probe-%d", index)
}
// err 表示第二次商品多规格探测错误。
if err := srv.enrichSyncedItemMultiSpec(context.Background(), client, "unb=1; _m_h5_tk=t_1;", "acc1", cachedItems); err != nil {
t.Fatalf("cached enrich multi spec: %v", err)
}
if probeCalls != 8 {
t.Fatalf("cached probe calls=%d want 8", probeCalls)
}
// flags、err 保存数据库批量标记查询结果及错误,确认本地查询未误报候选商品。
flags, err := store.Items.MultiSpecFlags(context.Background(), "acc1", []string{"probe-0"})
if err != nil || len(flags) != 0 {
@@ -685,6 +701,24 @@ func TestEnrichSyncedItemMultiSpecLimitsProbeConcurrency(t *testing.T) {
}
}
// TestItemSpecCacheExpires 验证商品多规格缓存过期后不会继续返回旧值。
func TestItemSpecCacheExpires(t *testing.T) {
// srv 是仅用于验证商品多规格缓存生命周期的服务实例。
srv := &Server{itemSpecCache: map[string]itemSpecCacheEntry{
itemSpecCacheKey("acc1", "item-1"): {isMultiSpec: true, expiresAt: time.Now().Add(-time.Second)},
}}
// value、ok 保存过期缓存的读取结果。
value, ok := srv.cachedItemSpec("acc1", "item-1")
if ok || value {
t.Fatalf("expired cache should miss: value=%v ok=%v", value, ok)
}
srv.cacheItemSpec("acc1", "item-1", false)
value, ok = srv.cachedItemSpec("acc1", "item-1")
if !ok || value {
t.Fatalf("fresh false cache mismatch: value=%v ok=%v", value, ok)
}
}
// TestSyncItemsFromAccountFail mtop 返回非成功 → 502。
func TestSyncItemsFromAccountFail(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
+5
View File
@@ -85,6 +85,10 @@ type Server struct {
reconciliation *reconciliation.Service
// transactionRepository 提供统一事务执行所需的最小持久化能力。
transactionRepository transactionRepository
// itemSpecCacheMu 保护商品多规格探测缓存。
itemSpecCacheMu sync.Mutex
// itemSpecCache 保存短期商品多规格探测结果,减少重复远端请求。
itemSpecCache map[string]itemSpecCacheEntry
publishMu sync.Mutex
publishCancels map[string]publishBatchWorker
@@ -154,6 +158,7 @@ func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr st
qrPersisted: make(map[string]qrLoginPersistence),
qrOwners: make(map[string]qrLoginOwner),
loginLimiter: newLoginFailureLimiter(),
itemSpecCache: make(map[string]itemSpecCacheEntry),
}
// option 表示当前遍历过程中的option
for _, option := range options {