Files
tyapi-server/internal/container/cache_setup.go
2025-07-31 15:41:00 +08:00

183 lines
4.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package container
import (
"context"
"time"
"go.uber.org/zap"
"gorm.io/gorm"
"tyapi-server/internal/config"
"tyapi-server/internal/shared/cache"
"tyapi-server/internal/shared/interfaces"
)
// SetupGormCache 设置GORM缓存插件
func SetupGormCache(db *gorm.DB, cacheService interfaces.CacheService, cfg *config.Config, logger *zap.Logger) error {
// 缓存功能已完全禁用
logger.Info("GORM缓存插件已禁用 - 所有查询将直接访问数据库")
return nil
// 以下是原有的缓存配置代码,已注释掉
/*
// 创建缓存配置
cacheConfig := cache.CacheConfig{
DefaultTTL: 30 * time.Minute,
TablePrefix: "gorm_cache",
MaxCacheSize: 1000,
CacheComplexSQL: false,
EnableStats: true,
EnableWarmup: true,
PenetrationGuard: true,
BloomFilter: false,
AutoInvalidate: true,
InvalidateDelay: 100 * time.Millisecond,
// 配置启用缓存的表
EnabledTables: []string{
// "product",
// "product_category",
// "enterprise_info_submit_records",
// "sms_codes",
// "wallets",
// "subscription",
// "product_category",
// "product_documentation",
// "enterprise_infos",
// "api_users",
// 添加更多需要缓存的表
},
// 配置禁用缓存的表(日志表等)
DisabledTables: []string{
"audit_logs", // 审计日志
"system_logs", // 系统日志
"operation_logs", // 操作日志
"api_calls", // API调用日志表变化频繁不适合缓存
},
}
// 初始化全局缓存配置管理器
cache.InitCacheConfigManager(cacheConfig)
// 创建缓存插件
cachePlugin := cache.NewGormCachePlugin(cacheService, logger, cacheConfig)
// 注册插件到GORM
if err := db.Use(cachePlugin); err != nil {
logger.Error("注册GORM缓存插件失败", zap.Error(err))
return err
}
logger.Info("GORM缓存插件已成功注册",
zap.Duration("default_ttl", cacheConfig.DefaultTTL),
zap.Strings("enabled_tables", cacheConfig.EnabledTables),
zap.Strings("disabled_tables", cacheConfig.DisabledTables),
)
*/
// return nil
}
// GetCacheConfig 根据环境获取缓存配置
func GetCacheConfig(cfg *config.Config) cache.CacheConfig {
// 生产环境配置
if cfg.Server.Mode == "release" {
cacheConfig := cache.CacheConfig{
DefaultTTL: 60 * time.Minute, // 生产环境延长缓存时间
TablePrefix: "prod_cache",
MaxCacheSize: 5000, // 生产环境增加缓存大小
CacheComplexSQL: false, // 生产环境不缓存复杂SQL
EnableStats: true,
EnableWarmup: true,
PenetrationGuard: true,
BloomFilter: true, // 生产环境启用布隆过滤器
AutoInvalidate: true,
InvalidateDelay: 50 * time.Millisecond,
EnabledTables: []string{
// "product",
// "product_category",
// "enterprise_info_submit_records",
// "sms_codes",
},
DisabledTables: []string{
"api_calls", // API调用日志表变化频繁不适合缓存
},
}
// 初始化全局缓存配置管理器
cache.InitCacheConfigManager(cacheConfig)
return cacheConfig
}
// 开发环境配置
cacheConfig := cache.CacheConfig{
DefaultTTL: 10 * time.Minute, // 开发环境缩短缓存时间,便于测试
TablePrefix: "dev_cache",
MaxCacheSize: 500,
CacheComplexSQL: true, // 开发环境允许缓存复杂SQL便于调试
EnableStats: true,
EnableWarmup: false, // 开发环境关闭预热
PenetrationGuard: false, // 开发环境关闭穿透保护
BloomFilter: false,
AutoInvalidate: true,
InvalidateDelay: 200 * time.Millisecond,
EnabledTables: []string{
// "product",
// "product_category",
// "enterprise_info_submit_records",
// "sms_codes",
},
DisabledTables: []string{
"api_calls", // API调用日志表变化频繁不适合缓存
},
}
// 初始化全局缓存配置管理器
cache.InitCacheConfigManager(cacheConfig)
return cacheConfig
}
// CacheMetrics 缓存性能指标
type CacheMetrics struct {
HitRate float64 `json:"hit_rate"`
MissRate float64 `json:"miss_rate"`
TotalHits int64 `json:"total_hits"`
TotalMisses int64 `json:"total_misses"`
CachedTables int `json:"cached_tables"`
CacheSize int64 `json:"cache_size"`
AvgResponseMs float64 `json:"avg_response_ms"`
}
// GetCacheMetrics 获取缓存性能指标
func GetCacheMetrics(cacheService interfaces.CacheService) (*CacheMetrics, error) {
stats, err := cacheService.Stats(context.Background())
if err != nil {
return nil, err
}
total := stats.Hits + stats.Misses
hitRate := float64(0)
missRate := float64(0)
if total > 0 {
hitRate = float64(stats.Hits) / float64(total) * 100
missRate = float64(stats.Misses) / float64(total) * 100
}
return &CacheMetrics{
HitRate: hitRate,
MissRate: missRate,
TotalHits: stats.Hits,
TotalMisses: stats.Misses,
CacheSize: stats.Memory,
CachedTables: int(stats.Keys),
}, nil
}