179 lines
4.7 KiB
Go
179 lines
4.7 KiB
Go
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",
|
||
"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{
|
||
"users",
|
||
"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{
|
||
"users",
|
||
"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
|
||
}
|