feat(lyra): 为分类查询添加缓存并同步项目约定
- 实现分类列表缓存查询与故障降级 - 统一缓存键命名 - 同步日志、响应、依赖组装及测试约定 - 移除 postgres 占位目录
This commit is contained in:
@@ -3,7 +3,11 @@ package model
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"lyra/internal/cache"
|
||||
"lyra/internal/pkg/constant"
|
||||
"lyra/internal/util"
|
||||
|
||||
sq "github.com/Masterminds/squirrel"
|
||||
"github.com/jmoiron/sqlx"
|
||||
@@ -27,7 +31,17 @@ type defaultCategoryModel struct {
|
||||
func NewCategoryModel(db *sqlx.DB, cache *cache.Cache) CategoryModel {
|
||||
return &defaultCategoryModel{db: db, cache: cache}
|
||||
}
|
||||
|
||||
const categoryListCacheTTL = 5 * time.Minute
|
||||
|
||||
func (m *defaultCategoryModel) FindAll(ctx context.Context) ([]*Category, error) {
|
||||
cached, hit, err := m.cache.Get[[]*Category](ctx, constant.CategoryListCacheKey)
|
||||
if err != nil {
|
||||
util.Logger(ctx).Error("读取分类列表缓存失败", "key", constant.CategoryListCacheKey, "error", err)
|
||||
}
|
||||
if hit {
|
||||
return cached, nil
|
||||
}
|
||||
|
||||
query, args, err := sq.
|
||||
Select("id", "slug", "title", "sort").
|
||||
@@ -45,5 +59,12 @@ func (m *defaultCategoryModel) FindAll(ctx context.Context) ([]*Category, error)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("数据库查询出错: %w", err)
|
||||
}
|
||||
return rows, err
|
||||
if err := m.cache.Set(ctx, cache.Entry[[]*Category]{
|
||||
Key: constant.CategoryListCacheKey,
|
||||
Value: rows,
|
||||
TTL: categoryListCacheTTL,
|
||||
}); err != nil {
|
||||
util.Logger(ctx).Error("写入分类列表缓存失败", "key", constant.CategoryListCacheKey, "error", err)
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user