fix: 修复账号列表首次加载窗口费用显示 $0.00
lite 模式下从快照缓存读取窗口费用,非 lite 模式查询后写入缓存
This commit is contained in:
@@ -288,8 +288,19 @@ func (h *AccountHandler) List(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 仅非 lite 模式获取窗口费用(PostgreSQL 聚合查询,高开销)
|
// 窗口费用获取:lite 模式从快照缓存读取,非 lite 模式执行 PostgreSQL 查询后写入缓存
|
||||||
if !lite && len(windowCostAccountIDs) > 0 {
|
if len(windowCostAccountIDs) > 0 {
|
||||||
|
if lite {
|
||||||
|
// lite 模式:尝试从快照缓存读取
|
||||||
|
cacheKey := buildWindowCostCacheKey(windowCostAccountIDs)
|
||||||
|
if cached, ok := accountWindowCostCache.Get(cacheKey); ok {
|
||||||
|
if costs, ok := cached.Payload.(map[int64]float64); ok {
|
||||||
|
windowCosts = costs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 缓存未命中则 windowCosts 保持 nil(仅发生在服务刚启动时)
|
||||||
|
} else {
|
||||||
|
// 非 lite 模式:执行 PostgreSQL 聚合查询(高开销)
|
||||||
windowCosts = make(map[int64]float64)
|
windowCosts = make(map[int64]float64)
|
||||||
var mu sync.Mutex
|
var mu sync.Mutex
|
||||||
g, gctx := errgroup.WithContext(c.Request.Context())
|
g, gctx := errgroup.WithContext(c.Request.Context())
|
||||||
@@ -314,6 +325,11 @@ func (h *AccountHandler) List(c *gin.Context) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
_ = g.Wait()
|
_ = g.Wait()
|
||||||
|
|
||||||
|
// 查询完毕后写入快照缓存,供 lite 模式使用
|
||||||
|
cacheKey := buildWindowCostCacheKey(windowCostAccountIDs)
|
||||||
|
accountWindowCostCache.Set(cacheKey, windowCosts)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build response with concurrency info
|
// Build response with concurrency info
|
||||||
|
|||||||
25
backend/internal/handler/admin/account_window_cost_cache.go
Normal file
25
backend/internal/handler/admin/account_window_cost_cache.go
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
package admin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var accountWindowCostCache = newSnapshotCache(30 * time.Second)
|
||||||
|
|
||||||
|
func buildWindowCostCacheKey(accountIDs []int64) string {
|
||||||
|
if len(accountIDs) == 0 {
|
||||||
|
return "accounts_window_cost_empty"
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
b.Grow(len(accountIDs) * 6)
|
||||||
|
_, _ = b.WriteString("accounts_window_cost:")
|
||||||
|
for i, id := range accountIDs {
|
||||||
|
if i > 0 {
|
||||||
|
_ = b.WriteByte(',')
|
||||||
|
}
|
||||||
|
_, _ = b.WriteString(strconv.FormatInt(id, 10))
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user