This commit is contained in:
2025-07-28 01:46:39 +08:00
parent b03129667a
commit 357639462a
219 changed files with 21634 additions and 8138 deletions

View File

@@ -8,6 +8,7 @@ import (
"go.uber.org/zap"
"gorm.io/gorm"
"tyapi-server/internal/shared/cache"
"tyapi-server/internal/shared/interfaces"
)
@@ -26,41 +27,112 @@ func NewCachedBaseRepositoryImpl(db *gorm.DB, logger *zap.Logger, tableName stri
}
}
// ================ 智能缓存决策方法 ================
// isTableCacheEnabled 检查表是否启用缓存
func (r *CachedBaseRepositoryImpl) isTableCacheEnabled() bool {
// 使用全局缓存配置管理器
if cache.GlobalCacheConfigManager != nil {
return cache.GlobalCacheConfigManager.IsTableCacheEnabled(r.tableName)
}
// 如果全局管理器未初始化,默认启用缓存
r.logger.Warn("全局缓存配置管理器未初始化,默认启用缓存",
zap.String("table", r.tableName))
return true
}
// shouldUseCacheForTable 智能判断是否应该对当前表使用缓存
func (r *CachedBaseRepositoryImpl) shouldUseCacheForTable() bool {
// 检查表是否启用缓存
if !r.isTableCacheEnabled() {
r.logger.Debug("表未启用缓存,跳过缓存操作",
zap.String("table", r.tableName))
return false
}
return true
}
// ================ 智能缓存方法 ================
// GetWithCache 带缓存的单条查询
// GetWithCache 带缓存的单条查询(智能决策)
func (r *CachedBaseRepositoryImpl) GetWithCache(ctx context.Context, dest interface{}, ttl time.Duration, where string, args ...interface{}) error {
db := r.GetDB(ctx).
Set("cache:enabled", true).
Set("cache:ttl", ttl)
db := r.GetDB(ctx)
// 智能决策:根据表配置决定是否使用缓存
if r.shouldUseCacheForTable() {
db = db.Set("cache:enabled", true).Set("cache:ttl", ttl)
r.logger.Debug("执行带缓存查询",
zap.String("table", r.tableName),
zap.Duration("ttl", ttl),
zap.String("where", where))
} else {
db = db.Set("cache:disabled", true)
r.logger.Debug("执行无缓存查询",
zap.String("table", r.tableName),
zap.String("where", where))
}
return db.Where(where, args...).First(dest).Error
}
// FindWithCache 带缓存的多条查询
// FindWithCache 带缓存的多条查询(智能决策)
func (r *CachedBaseRepositoryImpl) FindWithCache(ctx context.Context, dest interface{}, ttl time.Duration, where string, args ...interface{}) error {
db := r.GetDB(ctx).
Set("cache:enabled", true).
Set("cache:ttl", ttl)
db := r.GetDB(ctx)
// 智能决策:根据表配置决定是否使用缓存
if r.shouldUseCacheForTable() {
db = db.Set("cache:enabled", true).Set("cache:ttl", ttl)
r.logger.Debug("执行带缓存批量查询",
zap.String("table", r.tableName),
zap.Duration("ttl", ttl),
zap.String("where", where))
} else {
db = db.Set("cache:disabled", true)
r.logger.Debug("执行无缓存批量查询",
zap.String("table", r.tableName),
zap.String("where", where))
}
return db.Where(where, args...).Find(dest).Error
}
// CountWithCache 带缓存的计数查询
// CountWithCache 带缓存的计数查询(智能决策)
func (r *CachedBaseRepositoryImpl) CountWithCache(ctx context.Context, count *int64, ttl time.Duration, entity interface{}, where string, args ...interface{}) error {
db := r.GetDB(ctx).
Set("cache:enabled", true).
Set("cache:ttl", ttl).
Model(entity)
db := r.GetDB(ctx).Model(entity)
// 智能决策:根据表配置决定是否使用缓存
if r.shouldUseCacheForTable() {
db = db.Set("cache:enabled", true).Set("cache:ttl", ttl)
r.logger.Debug("执行带缓存计数查询",
zap.String("table", r.tableName),
zap.Duration("ttl", ttl),
zap.String("where", where))
} else {
db = db.Set("cache:disabled", true)
r.logger.Debug("执行无缓存计数查询",
zap.String("table", r.tableName),
zap.String("where", where))
}
return db.Where(where, args...).Count(count).Error
}
// ListWithCache 带缓存的列表查询
// ListWithCache 带缓存的列表查询(智能决策)
func (r *CachedBaseRepositoryImpl) ListWithCache(ctx context.Context, dest interface{}, ttl time.Duration, options CacheListOptions) error {
db := r.GetDB(ctx).
Set("cache:enabled", true).
Set("cache:ttl", ttl)
db := r.GetDB(ctx)
// 智能决策:根据表配置决定是否使用缓存
if r.shouldUseCacheForTable() {
db = db.Set("cache:enabled", true).Set("cache:ttl", ttl)
r.logger.Debug("执行带缓存列表查询",
zap.String("table", r.tableName),
zap.Duration("ttl", ttl))
} else {
db = db.Set("cache:disabled", true)
r.logger.Debug("执行无缓存列表查询",
zap.String("table", r.tableName))
}
// 应用where条件
if options.Where != "" {
@@ -90,12 +162,12 @@ func (r *CachedBaseRepositoryImpl) ListWithCache(ctx context.Context, dest inter
// CacheListOptions 缓存列表查询选项
type CacheListOptions struct {
Where string `json:"where"`
Args []interface{} `json:"args"`
Order string `json:"order"`
Limit int `json:"limit"`
Offset int `json:"offset"`
Preloads []string `json:"preloads"`
Where string `json:"where"`
Args []interface{} `json:"args"`
Order string `json:"order"`
Limit int `json:"limit"`
Offset int `json:"offset"`
Preloads []string `json:"preloads"`
}
// ================ 缓存控制方法 ================
@@ -142,6 +214,10 @@ func (r *CachedBaseRepositoryImpl) WithLongCache() *CachedBaseRepositoryImpl {
// SmartGetByID 智能ID查询自动缓存
func (r *CachedBaseRepositoryImpl) SmartGetByID(ctx context.Context, id string, dest interface{}) error {
r.logger.Debug("执行智能ID查询",
zap.String("table", r.tableName),
zap.String("id", id))
return r.GetWithCache(ctx, dest, 30*time.Minute, "id = ?", id)
}
@@ -151,7 +227,7 @@ func (r *CachedBaseRepositoryImpl) SmartGetByField(ctx context.Context, dest int
if len(ttl) > 0 {
cacheTTL = ttl[0]
}
return r.GetWithCache(ctx, dest, cacheTTL, field+" = ?", value)
}
@@ -161,6 +237,12 @@ func (r *CachedBaseRepositoryImpl) SmartList(ctx context.Context, dest interface
cacheTTL := r.calculateCacheTTL(options)
useCache := r.shouldUseCache(options)
r.logger.Debug("执行智能列表查询",
zap.String("table", r.tableName),
zap.Bool("use_cache", useCache),
zap.Duration("cache_ttl", cacheTTL))
// 修复:确保缓存标记在查询前正确设置
db := r.GetDB(ctx)
if useCache {
db = db.Set("cache:enabled", true).Set("cache:ttl", cacheTTL)
@@ -254,14 +336,14 @@ func (r *CachedBaseRepositoryImpl) shouldUseCache(options interfaces.ListOptions
// WarmupCommonQueries 预热常用查询
func (r *CachedBaseRepositoryImpl) WarmupCommonQueries(ctx context.Context, queries []WarmupQuery) error {
r.logger.Info("开始预热缓存",
r.logger.Info("开始预热缓存",
zap.String("table", r.tableName),
zap.Int("queries", len(queries)),
)
for _, query := range queries {
if err := r.executeWarmupQuery(ctx, query); err != nil {
r.logger.Warn("缓存预热失败",
r.logger.Warn("缓存预热失败",
zap.String("query", query.Name),
zap.Error(err),
)
@@ -273,11 +355,11 @@ func (r *CachedBaseRepositoryImpl) WarmupCommonQueries(ctx context.Context, quer
// WarmupQuery 预热查询定义
type WarmupQuery struct {
Name string `json:"name"`
SQL string `json:"sql"`
Args []interface{} `json:"args"`
TTL time.Duration `json:"ttl"`
Dest interface{} `json:"dest"`
Name string `json:"name"`
SQL string `json:"sql"`
Args []interface{} `json:"args"`
TTL time.Duration `json:"ttl"`
Dest interface{} `json:"dest"`
}
// executeWarmupQuery 执行预热查询
@@ -313,7 +395,7 @@ func (r *CachedBaseRepositoryImpl) GetOrCreate(ctx context.Context, dest interfa
if err := r.CreateEntity(ctx, newEntity); err != nil {
return err
}
// 将新创建的实体复制到dest
// 这里需要反射或其他方式复制
return nil
@@ -333,7 +415,7 @@ func (r *CachedBaseRepositoryImpl) BatchGetWithCache(ctx context.Context, ids []
// RefreshCache 刷新缓存
func (r *CachedBaseRepositoryImpl) RefreshCache(ctx context.Context, pattern string) error {
r.logger.Info("刷新缓存",
r.logger.Info("刷新缓存",
zap.String("table", r.tableName),
zap.String("pattern", pattern),
)
@@ -348,9 +430,9 @@ func (r *CachedBaseRepositoryImpl) RefreshCache(ctx context.Context, pattern str
// GetCacheInfo 获取缓存信息
func (r *CachedBaseRepositoryImpl) GetCacheInfo() map[string]interface{} {
return map[string]interface{}{
"table_name": r.tableName,
"cache_enabled": true,
"default_ttl": "30m",
"table_name": r.tableName,
"cache_enabled": true,
"default_ttl": "30m",
"cache_patterns": []string{
fmt.Sprintf("gorm_cache:%s:*", r.tableName),
},
@@ -359,9 +441,9 @@ func (r *CachedBaseRepositoryImpl) GetCacheInfo() map[string]interface{} {
// LogCacheOperation 记录缓存操作
func (r *CachedBaseRepositoryImpl) LogCacheOperation(operation, details string) {
r.logger.Debug("缓存操作",
r.logger.Debug("缓存操作",
zap.String("table", r.tableName),
zap.String("operation", operation),
zap.String("details", details),
)
}
}