feat: 首页增加内存缓存(30s TTL)
- 新增 internal/cache/home_cache.go,实现带 TTL 的首页文章列表内存缓存 - frontend.go 首页 handler 优先读取缓存,未命中/过期时查询 DB 并回填 - PostService 注入失效回调,在 Create/Update/Delete/Approve 后自动失效缓存 - 减少首页每次请求都查 DB 的开销
This commit is contained in:
@ -4,6 +4,7 @@ import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"metazone.cc/metalab/internal/cache"
|
||||
"metazone.cc/metalab/internal/config"
|
||||
"metazone.cc/metalab/internal/controller"
|
||||
adminCtrl "metazone.cc/metalab/internal/controller/admin"
|
||||
@ -42,6 +43,7 @@ type dependencies struct {
|
||||
favoriteCtrl *controller.FavoriteController
|
||||
favoriteService *service.FavoriteService
|
||||
trendsService *service.TrendsService
|
||||
homeCache *cache.HomePageCache
|
||||
}
|
||||
|
||||
func buildDepsCore(db *gorm.DB, cfg *config.Config, siteSettings *config.SiteSettings, redisClient *redis.Client) (
|
||||
|
||||
@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@ -22,10 +22,16 @@ func setupFrontendRoutes(r *gin.Engine, cfg *config.Config, d *dependencies) {
|
||||
})
|
||||
{
|
||||
pages.GET("/", func(c *gin.Context) {
|
||||
posts, total, err := d.postService.List("", 1, 6)
|
||||
if err != nil {
|
||||
posts = nil
|
||||
total = 0
|
||||
posts, total, ok := d.homeCache.Get()
|
||||
if !ok {
|
||||
var err error
|
||||
posts, total, err = d.postService.List("", 1, 6)
|
||||
if err != nil {
|
||||
posts = nil
|
||||
total = 0
|
||||
} else {
|
||||
d.homeCache.Set(posts, total)
|
||||
}
|
||||
}
|
||||
c.HTML(http.StatusOK, "home/index.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "首页",
|
||||
|
||||
Reference in New Issue
Block a user