temp
This commit is contained in:
153
internal/container/cache_setup.go
Normal file
153
internal/container/cache_setup.go
Normal file
@@ -0,0 +1,153 @@
|
||||
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
|
||||
}
|
||||
@@ -2,40 +2,37 @@ package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"go.uber.org/fx"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"tyapi-server/internal/application/admin"
|
||||
"tyapi-server/internal/application/certification"
|
||||
"tyapi-server/internal/application/finance"
|
||||
"tyapi-server/internal/application/product"
|
||||
"tyapi-server/internal/application/user"
|
||||
"tyapi-server/internal/config"
|
||||
domain_admin_repo "tyapi-server/internal/domains/admin/repositories"
|
||||
admin_service "tyapi-server/internal/domains/admin/services"
|
||||
domain_certification_repo "tyapi-server/internal/domains/certification/repositories"
|
||||
certification_service "tyapi-server/internal/domains/certification/services"
|
||||
domain_finance_repo "tyapi-server/internal/domains/finance/repositories"
|
||||
finance_service "tyapi-server/internal/domains/finance/services"
|
||||
domain_product_repo "tyapi-server/internal/domains/product/repositories"
|
||||
product_service "tyapi-server/internal/domains/product/services"
|
||||
domain_user_repo "tyapi-server/internal/domains/user/repositories"
|
||||
user_service "tyapi-server/internal/domains/user/services"
|
||||
"tyapi-server/internal/infrastructure/cache"
|
||||
"tyapi-server/internal/infrastructure/database"
|
||||
admin_repo "tyapi-server/internal/infrastructure/database/repositories/admin"
|
||||
certification_repo "tyapi-server/internal/infrastructure/database/repositories/certification"
|
||||
finance_repo "tyapi-server/internal/infrastructure/database/repositories/finance"
|
||||
product_repo "tyapi-server/internal/infrastructure/database/repositories/product"
|
||||
user_repo "tyapi-server/internal/infrastructure/database/repositories/user"
|
||||
"tyapi-server/internal/infrastructure/external/ocr"
|
||||
"tyapi-server/internal/infrastructure/external/sms"
|
||||
"tyapi-server/internal/infrastructure/external/storage"
|
||||
"tyapi-server/internal/infrastructure/http/handlers"
|
||||
"tyapi-server/internal/infrastructure/http/routes"
|
||||
shared_database "tyapi-server/internal/shared/database"
|
||||
"tyapi-server/internal/shared/esign"
|
||||
"tyapi-server/internal/shared/events"
|
||||
"tyapi-server/internal/shared/health"
|
||||
"tyapi-server/internal/shared/hooks"
|
||||
@@ -49,6 +46,10 @@ import (
|
||||
"tyapi-server/internal/shared/saga"
|
||||
sharedStorage "tyapi-server/internal/shared/storage"
|
||||
"tyapi-server/internal/shared/tracing"
|
||||
"tyapi-server/internal/shared/validator"
|
||||
|
||||
domain_user_repo "tyapi-server/internal/domains/user/repositories"
|
||||
user_repo "tyapi-server/internal/infrastructure/database/repositories/user"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
@@ -92,7 +93,7 @@ func NewContainer() *Container {
|
||||
return defaultLogger
|
||||
},
|
||||
// 数据库连接
|
||||
func(cfg *config.Config) (*gorm.DB, error) {
|
||||
func(cfg *config.Config, cacheService interfaces.CacheService, logger *zap.Logger) (*gorm.DB, error) {
|
||||
dbCfg := database.Config{
|
||||
Host: cfg.Database.Host,
|
||||
Port: cfg.Database.Port,
|
||||
@@ -109,6 +110,13 @@ func NewContainer() *Container {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 设置GORM缓存插件
|
||||
if err := SetupGormCache(db.DB, cacheService, cfg, logger); err != nil {
|
||||
logger.Warn("GORM缓存插件设置失败", zap.Error(err))
|
||||
// 不返回错误,允许系统在没有缓存的情况下运行
|
||||
}
|
||||
|
||||
return db.DB, nil
|
||||
},
|
||||
// Redis客户端
|
||||
@@ -132,6 +140,10 @@ func NewContainer() *Container {
|
||||
func(cfg *config.Config) config.AppConfig {
|
||||
return cfg.App
|
||||
},
|
||||
// 事务管理器
|
||||
func(db *gorm.DB, logger *zap.Logger) *shared_database.TransactionManager {
|
||||
return shared_database.NewTransactionManager(db, logger)
|
||||
},
|
||||
// 短信服务
|
||||
sms.NewAliSMSService,
|
||||
// 存储服务
|
||||
@@ -158,6 +170,19 @@ func NewContainer() *Container {
|
||||
},
|
||||
fx.As(new(sharedOCR.OCRService)),
|
||||
),
|
||||
// e签宝服务
|
||||
func(cfg *config.Config) *esign.Client {
|
||||
esignConfig, err := esign.NewConfig(
|
||||
cfg.Esign.AppID,
|
||||
cfg.Esign.AppSecret,
|
||||
cfg.Esign.ServerURL,
|
||||
cfg.Esign.TemplateID,
|
||||
)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("e签宝配置创建失败: %v", err))
|
||||
}
|
||||
return esign.NewClient(esignConfig)
|
||||
},
|
||||
),
|
||||
|
||||
// 高级特性模块
|
||||
@@ -185,7 +210,7 @@ func NewContainer() *Container {
|
||||
// HTTP基础组件
|
||||
fx.Provide(
|
||||
sharedhttp.NewResponseBuilder,
|
||||
sharedhttp.NewRequestValidatorZh,
|
||||
validator.NewRequestValidator,
|
||||
sharedhttp.NewGinRouter,
|
||||
),
|
||||
|
||||
@@ -199,6 +224,7 @@ func NewContainer() *Container {
|
||||
NewRequestLoggerMiddlewareWrapper,
|
||||
middleware.NewJWTAuthMiddleware,
|
||||
middleware.NewOptionalAuthMiddleware,
|
||||
middleware.NewAdminAuthMiddleware,
|
||||
middleware.NewTraceIDMiddleware,
|
||||
middleware.NewErrorTrackingMiddleware,
|
||||
NewRequestBodyLoggerMiddlewareWrapper,
|
||||
@@ -223,30 +249,6 @@ func NewContainer() *Container {
|
||||
),
|
||||
),
|
||||
|
||||
// 仓储层 - 管理员域
|
||||
fx.Provide(
|
||||
// 管理员仓储 - 同时注册具体类型和接口类型
|
||||
fx.Annotate(
|
||||
admin_repo.NewGormAdminRepository,
|
||||
fx.As(new(domain_admin_repo.AdminRepository)),
|
||||
),
|
||||
// 管理员登录日志仓储
|
||||
fx.Annotate(
|
||||
admin_repo.NewGormAdminLoginLogRepository,
|
||||
fx.As(new(domain_admin_repo.AdminLoginLogRepository)),
|
||||
),
|
||||
// 管理员操作日志仓储
|
||||
fx.Annotate(
|
||||
admin_repo.NewGormAdminOperationLogRepository,
|
||||
fx.As(new(domain_admin_repo.AdminOperationLogRepository)),
|
||||
),
|
||||
// 管理员权限仓储
|
||||
fx.Annotate(
|
||||
admin_repo.NewGormAdminPermissionRepository,
|
||||
fx.As(new(domain_admin_repo.AdminPermissionRepository)),
|
||||
),
|
||||
),
|
||||
|
||||
// 仓储层 - 认证域
|
||||
fx.Provide(
|
||||
// 认证申请仓储
|
||||
@@ -254,25 +256,20 @@ func NewContainer() *Container {
|
||||
certification_repo.NewGormCertificationRepository,
|
||||
fx.As(new(domain_certification_repo.CertificationRepository)),
|
||||
),
|
||||
// 人脸识别记录仓储
|
||||
// 企业信息提交记录仓储
|
||||
fx.Annotate(
|
||||
certification_repo.NewGormFaceVerifyRecordRepository,
|
||||
fx.As(new(domain_certification_repo.FaceVerifyRecordRepository)),
|
||||
certification_repo.NewGormEnterpriseInfoSubmitRecordRepository,
|
||||
fx.As(new(domain_certification_repo.EnterpriseInfoSubmitRecordRepository)),
|
||||
),
|
||||
// 合同记录仓储
|
||||
// e签宝生成合同记录仓储
|
||||
fx.Annotate(
|
||||
certification_repo.NewGormContractRecordRepository,
|
||||
fx.As(new(domain_certification_repo.ContractRecordRepository)),
|
||||
certification_repo.NewGormEsignContractGenerateRecordRepository,
|
||||
fx.As(new(domain_certification_repo.EsignContractGenerateRecordRepository)),
|
||||
),
|
||||
// 营业执照上传记录仓储
|
||||
// e签宝签署合同记录仓储
|
||||
fx.Annotate(
|
||||
certification_repo.NewGormLicenseUploadRecordRepository,
|
||||
fx.As(new(domain_certification_repo.LicenseUploadRecordRepository)),
|
||||
),
|
||||
// 通知记录仓储
|
||||
fx.Annotate(
|
||||
certification_repo.NewGormNotificationRecordRepository,
|
||||
fx.As(new(domain_certification_repo.NotificationRecordRepository)),
|
||||
certification_repo.NewGormEsignContractSignRecordRepository,
|
||||
fx.As(new(domain_certification_repo.EsignContractSignRecordRepository)),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -311,14 +308,18 @@ func NewContainer() *Container {
|
||||
|
||||
// 领域服务
|
||||
fx.Provide(
|
||||
user_service.NewUserService,
|
||||
user_service.NewUserManagementService,
|
||||
user_service.NewUserAuthService,
|
||||
user_service.NewSMSCodeService,
|
||||
user_service.NewEnterpriseService,
|
||||
admin_service.NewAdminService,
|
||||
certification_service.NewCertificationService,
|
||||
product_service.NewProductManagementService,
|
||||
product_service.NewProductSubscriptionService,
|
||||
certification_service.NewCertificationManagementService,
|
||||
certification_service.NewCertificationWorkflowService,
|
||||
certification_service.NewCertificationStateMachine,
|
||||
certification_service.NewEnterpriseInfoSubmitRecordService,
|
||||
certification_service.NewCertificationEsignService,
|
||||
finance_service.NewFinanceService,
|
||||
product_service.NewProductService,
|
||||
),
|
||||
|
||||
// 应用服务
|
||||
@@ -328,16 +329,16 @@ func NewContainer() *Container {
|
||||
user.NewUserApplicationService,
|
||||
fx.As(new(user.UserApplicationService)),
|
||||
),
|
||||
// 管理员应用服务 - 绑定到接口
|
||||
fx.Annotate(
|
||||
admin.NewAdminApplicationService,
|
||||
fx.As(new(admin.AdminApplicationService)),
|
||||
),
|
||||
// 认证应用服务 - 绑定到接口
|
||||
fx.Annotate(
|
||||
certification.NewCertificationApplicationService,
|
||||
fx.As(new(certification.CertificationApplicationService)),
|
||||
),
|
||||
// e签宝回调应用服务 - 绑定到接口
|
||||
fx.Annotate(
|
||||
certification.NewEsignCallbackApplicationService,
|
||||
fx.As(new(certification.EsignCallbackApplicationService)),
|
||||
),
|
||||
// 财务应用服务 - 绑定到接口
|
||||
fx.Annotate(
|
||||
finance.NewFinanceApplicationService,
|
||||
@@ -364,28 +365,28 @@ func NewContainer() *Container {
|
||||
fx.Provide(
|
||||
// 用户HTTP处理器
|
||||
handlers.NewUserHandler,
|
||||
// 管理员HTTP处理器
|
||||
handlers.NewAdminHandler,
|
||||
// 认证HTTP处理器
|
||||
handlers.NewCertificationHandler,
|
||||
// 财务HTTP处理器
|
||||
handlers.NewFinanceHandler,
|
||||
// 产品HTTP处理器
|
||||
handlers.NewProductHandler,
|
||||
// 产品管理员HTTP处理器
|
||||
handlers.NewProductAdminHandler,
|
||||
),
|
||||
|
||||
// 路由注册
|
||||
fx.Provide(
|
||||
// 用户路由
|
||||
routes.NewUserRoutes,
|
||||
// 管理员路由
|
||||
routes.NewAdminRoutes,
|
||||
// 认证路由
|
||||
routes.NewCertificationRoutes,
|
||||
// 财务路由
|
||||
routes.NewFinanceRoutes,
|
||||
// 产品路由
|
||||
routes.NewProductRoutes,
|
||||
// 产品管理员路由
|
||||
routes.NewProductAdminRoutes,
|
||||
),
|
||||
|
||||
// 应用生命周期
|
||||
@@ -460,10 +461,10 @@ func RegisterMiddlewares(
|
||||
func RegisterRoutes(
|
||||
router *sharedhttp.GinRouter,
|
||||
userRoutes *routes.UserRoutes,
|
||||
adminRoutes *routes.AdminRoutes,
|
||||
certificationRoutes *routes.CertificationRoutes,
|
||||
financeRoutes *routes.FinanceRoutes,
|
||||
productRoutes *routes.ProductRoutes,
|
||||
productAdminRoutes *routes.ProductAdminRoutes,
|
||||
cfg *config.Config,
|
||||
logger *zap.Logger,
|
||||
) {
|
||||
@@ -471,10 +472,10 @@ func RegisterRoutes(
|
||||
|
||||
// 注册所有路由
|
||||
userRoutes.Register(router)
|
||||
adminRoutes.Register(router)
|
||||
certificationRoutes.Register(router)
|
||||
financeRoutes.Register(router)
|
||||
productRoutes.Register(router)
|
||||
productAdminRoutes.Register(router)
|
||||
|
||||
// 打印注册的路由信息
|
||||
router.PrintRoutes()
|
||||
|
||||
Reference in New Issue
Block a user