feat: 首页增加内存缓存(30s TTL)

- 新增 internal/cache/home_cache.go,实现带 TTL 的首页文章列表内存缓存
- frontend.go 首页 handler 优先读取缓存,未命中/过期时查询 DB 并回填
- PostService 注入失效回调,在 Create/Update/Delete/Approve 后自动失效缓存
- 减少首页每次请求都查 DB 的开销
This commit is contained in:
2026-06-02 17:20:59 +08:00
parent 3e0fed80ce
commit 593b52096f
6 changed files with 110 additions and 11 deletions

View File

@ -1,6 +1,9 @@
package router
import (
"time"
"metazone.cc/metalab/internal/cache"
"metazone.cc/metalab/internal/config"
"metazone.cc/metalab/internal/controller"
adminCtrl "metazone.cc/metalab/internal/controller/admin"
@ -99,6 +102,10 @@ func buildDeps(db *gorm.DB, cfg *config.Config, siteSettings *config.SiteSetting
maintenanceMdw := middleware.NewMaintenanceMiddleware(cfg, siteSettings, sessionMgr)
// 首页内存缓存30s TTL文章变更时失效
homeCache := cache.NewHomePageCache(30 * time.Second)
postService.WithHomePageInvalidator(func() { homeCache.Invalidate() })
return &dependencies{
authCtrl: authCtrl, authMdw: authMdw, maintenanceMdw: maintenanceMdw,
settingsCtrl: settingsCtrl,
@ -119,5 +126,6 @@ func buildDeps(db *gorm.DB, cfg *config.Config, siteSettings *config.SiteSetting
favoriteCtrl: favoriteCtrl,
favoriteService: favoriteService,
trendsService: trendsService,
homeCache: homeCache,
}
}