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

176 lines
4.7 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,
2025-07-28 01:46:39 +08:00
2025-07-20 20:53:26 +08:00
// 配置启用缓存的表
EnabledTables: []string{
2025-07-28 01:46:39 +08:00
"product",
"product_category",
2025-07-20 20:53:26 +08:00
"enterprise_info_submit_records",
2025-07-28 01:46:39 +08:00
"sms_codes",
"wallets",
"subscription",
"product_category",
"product_documentation",
"enterprise_infos",
"api_users",
2025-07-20 20:53:26 +08:00
// 添加更多需要缓存的表
},
2025-07-28 01:46:39 +08:00
2025-07-20 20:53:26 +08:00
// 配置禁用缓存的表(日志表等)
DisabledTables: []string{
2025-07-28 01:46:39 +08:00
"audit_logs", // 审计日志
"system_logs", // 系统日志
"operation_logs", // 操作日志
"api_calls", // API调用日志表变化频繁不适合缓存
2025-07-20 20:53:26 +08:00
},
}
2025-07-28 01:46:39 +08:00
// 初始化全局缓存配置管理器
cache.InitCacheConfigManager(cacheConfig)
2025-07-20 20:53:26 +08:00
// 创建缓存插件
cachePlugin := cache.NewGormCachePlugin(cacheService, logger, cacheConfig)
// 注册插件到GORM
if err := db.Use(cachePlugin); err != nil {
logger.Error("注册GORM缓存插件失败", zap.Error(err))
return err
}
2025-07-28 01:46:39 +08:00
logger.Info("GORM缓存插件已成功注册",
2025-07-20 20:53:26 +08:00
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" {
2025-07-28 01:46:39 +08:00
cacheConfig := cache.CacheConfig{
DefaultTTL: 60 * time.Minute, // 生产环境延长缓存时间
2025-07-20 20:53:26 +08:00
TablePrefix: "prod_cache",
2025-07-28 01:46:39 +08:00
MaxCacheSize: 5000, // 生产环境增加缓存大小
CacheComplexSQL: false, // 生产环境不缓存复杂SQL
2025-07-20 20:53:26 +08:00
EnableStats: true,
EnableWarmup: true,
PenetrationGuard: true,
2025-07-28 01:46:39 +08:00
BloomFilter: true, // 生产环境启用布隆过滤器
2025-07-20 20:53:26 +08:00
AutoInvalidate: true,
InvalidateDelay: 50 * time.Millisecond,
2025-07-28 01:46:39 +08:00
2025-07-20 20:53:26 +08:00
EnabledTables: []string{
2025-07-28 01:46:39 +08:00
"product",
"product_category",
"enterprise_info_submit_records",
"sms_codes",
2025-07-20 20:53:26 +08:00
},
2025-07-28 01:46:39 +08:00
2025-07-20 20:53:26 +08:00
DisabledTables: []string{
2025-07-28 01:46:39 +08:00
"api_calls", // API调用日志表变化频繁不适合缓存
2025-07-20 20:53:26 +08:00
},
}
2025-07-28 01:46:39 +08:00
// 初始化全局缓存配置管理器
cache.InitCacheConfigManager(cacheConfig)
return cacheConfig
2025-07-20 20:53:26 +08:00
}
// 开发环境配置
2025-07-28 01:46:39 +08:00
cacheConfig := cache.CacheConfig{
DefaultTTL: 10 * time.Minute, // 开发环境缩短缓存时间,便于测试
2025-07-20 20:53:26 +08:00
TablePrefix: "dev_cache",
MaxCacheSize: 500,
2025-07-28 01:46:39 +08:00
CacheComplexSQL: true, // 开发环境允许缓存复杂SQL便于调试
2025-07-20 20:53:26 +08:00
EnableStats: true,
2025-07-28 01:46:39 +08:00
EnableWarmup: false, // 开发环境关闭预热
PenetrationGuard: false, // 开发环境关闭穿透保护
2025-07-20 20:53:26 +08:00
BloomFilter: false,
AutoInvalidate: true,
InvalidateDelay: 200 * time.Millisecond,
2025-07-28 01:46:39 +08:00
2025-07-20 20:53:26 +08:00
EnabledTables: []string{
2025-07-28 01:46:39 +08:00
"product",
"product_category",
"enterprise_info_submit_records",
"sms_codes",
2025-07-20 20:53:26 +08:00
},
2025-07-28 01:46:39 +08:00
2025-07-20 20:53:26 +08:00
DisabledTables: []string{
2025-07-28 01:46:39 +08:00
"api_calls", // API调用日志表变化频繁不适合缓存
2025-07-20 20:53:26 +08:00
},
}
2025-07-28 01:46:39 +08:00
// 初始化全局缓存配置管理器
cache.InitCacheConfigManager(cacheConfig)
return cacheConfig
2025-07-20 20:53:26 +08:00
}
// 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)
2025-07-28 01:46:39 +08:00
2025-07-20 20:53:26 +08:00
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
2025-07-28 01:46:39 +08:00
}