Files
tyapi-server/internal/container/cache_setup.go

153 lines
4.3 KiB
Go
Raw Normal View History

2025-07-20 20:53:26 +08:00
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 {
// 创建缓存配置
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{
"users",
"products",
"product_categories",
"enterprise_info_submit_records",
// 添加更多需要缓存的表
},
// 配置禁用缓存的表(日志表等)
DisabledTables: []string{
"sms_codes", // 短信验证码变化频繁
"audit_logs", // 审计日志
"system_logs", // 系统日志
"operation_logs", // 操作日志
},
}
// 创建缓存插件
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" {
return 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{
"users", "products", "product_categories",
"enterprise_info_submit_records", "certifications",
"product_documentations",
},
DisabledTables: []string{
"sms_codes", "audit_logs", "system_logs",
"operation_logs", "sessions", "api_keys",
},
}
}
// 开发环境配置
return 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{
"users", "products", "product_categories",
},
DisabledTables: []string{
"sms_codes", "audit_logs",
},
}
}
// 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
}