package binanceservice import ( "fmt" "time" "github.com/shopspring/decimal" ) // OptimizedConfig 优化配置结构 type OptimizedConfig struct { // 锁配置 LockConfig LockConfig `json:"lock_config"` // 重试配置 RetryConfig RetryConfig `json:"retry_config"` // 熔断器配置 CircuitBreakerConfig CircuitBreakerConfig `json:"circuit_breaker_config"` // 同步配置 SyncConfig SyncConfig `json:"sync_config"` // 性能配置 PerformanceConfig PerformanceConfig `json:"performance_config"` // 监控配置 MonitorConfig MonitorConfig `json:"monitor_config"` } // LockConfig 锁配置 type LockConfig struct { // Redis分布式锁超时时间 RedisLockTimeout time.Duration `json:"redis_lock_timeout"` // 获取锁等待时间 LockWaitTimeout time.Duration `json:"lock_wait_timeout"` // 订单处理锁前缀 OrderLockPrefix string `json:"order_lock_prefix"` // 持仓更新锁前缀 PositionLockPrefix string `json:"position_lock_prefix"` // 止盈止损锁前缀 TakeProfitLockPrefix string `json:"take_profit_lock_prefix"` } // CircuitBreakerConfig 熔断器配置 type CircuitBreakerConfig struct { Enabled bool `json:"enabled"` FailureThreshold int `json:"failure_threshold"` SuccessThreshold int `json:"success_threshold"` Timeout time.Duration `json:"timeout"` HalfOpenMaxCalls int `json:"half_open_max_calls"` } // RetryConfig 重试配置 type RetryConfig struct { // 最大重试次数 MaxRetries int `json:"max_retries"` // 重试延迟 RetryDelay time.Duration `json:"retry_delay"` // 指数退避因子 BackoffFactor float64 `json:"backoff_factor"` // 最大重试延迟 MaxRetryDelay time.Duration `json:"max_retry_delay"` // API调用重试次数 ApiRetryCount int `json:"api_retry_count"` // 数据库操作重试次数 DbRetryCount int `json:"db_retry_count"` } // SyncConfig 同步配置 type SyncConfig struct { // 持仓同步检查间隔 PositionSyncInterval time.Duration `json:"position_sync_interval"` // 持仓差异阈值 PositionDiffThreshold decimal.Decimal `json:"position_diff_threshold"` // 强制同步阈值 ForceSyncThreshold decimal.Decimal `json:"force_sync_threshold"` // 同步超时时间 SyncTimeout time.Duration `json:"sync_timeout"` // 是否启用自动同步 AutoSyncEnabled bool `json:"auto_sync_enabled"` } // PerformanceConfig 性能配置 type PerformanceConfig struct { // 批量操作大小 BatchSize int `json:"batch_size"` // 异步处理队列大小 AsyncQueueSize int `json:"async_queue_size"` // 工作协程数量 WorkerCount int `json:"worker_count"` // 数据库连接池大小 DbPoolSize int `json:"db_pool_size"` // 缓存过期时间 CacheExpiration time.Duration `json:"cache_expiration"` // 是否启用缓存 CacheEnabled bool `json:"cache_enabled"` } // MonitorConfig 监控配置 type MonitorConfig struct { // 是否启用监控 Enabled bool `json:"enabled"` // 监控数据收集间隔 CollectInterval time.Duration `json:"collect_interval"` // 告警阈值配置 AlertThresholds AlertThresholds `json:"alert_thresholds"` // 日志级别 LogLevel string `json:"log_level"` // 是否启用性能分析 ProfileEnabled bool `json:"profile_enabled"` } // AlertThresholds 告警阈值配置 type AlertThresholds struct { // 订单处理失败率阈值 (百分比) OrderFailureRate float64 `json:"order_failure_rate"` // 持仓同步失败率阈值 (百分比) PositionSyncFailureRate float64 `json:"position_sync_failure_rate"` // API调用失败率阈值 (百分比) ApiFailureRate float64 `json:"api_failure_rate"` // 响应时间阈值 (毫秒) ResponseTimeThreshold time.Duration `json:"response_time_threshold"` // 内存使用率阈值 (百分比) MemoryUsageThreshold float64 `json:"memory_usage_threshold"` // CPU使用率阈值 (百分比) CpuUsageThreshold float64 `json:"cpu_usage_threshold"` } // GetDefaultOptimizedConfig 获取默认优化配置 func GetDefaultOptimizedConfig() *OptimizedConfig { return &OptimizedConfig{ LockConfig: LockConfig{ RedisLockTimeout: 30 * time.Second, LockWaitTimeout: 5 * time.Second, OrderLockPrefix: "reverse_order_lock:", PositionLockPrefix: "position_update_lock:", TakeProfitLockPrefix: "take_profit_lock:", }, RetryConfig: RetryConfig{ MaxRetries: 3, RetryDelay: time.Second, BackoffFactor: 2.0, MaxRetryDelay: 10 * time.Second, ApiRetryCount: 3, DbRetryCount: 3, }, CircuitBreakerConfig: CircuitBreakerConfig{ Enabled: true, FailureThreshold: 5, SuccessThreshold: 3, Timeout: 60 * time.Second, HalfOpenMaxCalls: 3, }, SyncConfig: SyncConfig{ PositionSyncInterval: 30 * time.Second, PositionDiffThreshold: decimal.NewFromFloat(0.001), ForceSyncThreshold: decimal.NewFromFloat(0.01), SyncTimeout: 10 * time.Second, AutoSyncEnabled: true, }, PerformanceConfig: PerformanceConfig{ BatchSize: 10, AsyncQueueSize: 1000, WorkerCount: 5, DbPoolSize: 20, CacheExpiration: 5 * time.Minute, CacheEnabled: true, }, MonitorConfig: MonitorConfig{ Enabled: true, CollectInterval: time.Minute, AlertThresholds: AlertThresholds{ OrderFailureRate: 5.0, // 5% PositionSyncFailureRate: 2.0, // 2% ApiFailureRate: 10.0, // 10% ResponseTimeThreshold: 5 * time.Second, MemoryUsageThreshold: 80.0, // 80% CpuUsageThreshold: 70.0, // 70% }, LogLevel: "info", ProfileEnabled: false, }, } } // ValidateConfig 验证配置有效性 func (c *OptimizedConfig) ValidateConfig() error { // 验证锁配置 if c.LockConfig.RedisLockTimeout <= 0 { return fmt.Errorf("Redis锁超时时间必须大于0") } if c.LockConfig.LockWaitTimeout <= 0 { return fmt.Errorf("锁等待超时时间必须大于0") } // 验证重试配置 if c.RetryConfig.MaxRetries < 0 { return fmt.Errorf("最大重试次数不能为负数") } if c.RetryConfig.RetryDelay <= 0 { return fmt.Errorf("重试延迟必须大于0") } if c.RetryConfig.BackoffFactor <= 1.0 { return fmt.Errorf("退避因子必须大于1.0") } // 验证同步配置 if c.SyncConfig.PositionSyncInterval <= 0 { return fmt.Errorf("持仓同步间隔必须大于0") } if c.SyncConfig.PositionDiffThreshold.IsNegative() { return fmt.Errorf("持仓差异阈值不能为负数") } // 验证性能配置 if c.PerformanceConfig.BatchSize <= 0 { return fmt.Errorf("批量操作大小必须大于0") } if c.PerformanceConfig.WorkerCount <= 0 { return fmt.Errorf("工作协程数量必须大于0") } if c.PerformanceConfig.DbPoolSize <= 0 { return fmt.Errorf("数据库连接池大小必须大于0") } // 验证监控配置 if c.MonitorConfig.Enabled { if c.MonitorConfig.CollectInterval <= 0 { return fmt.Errorf("监控数据收集间隔必须大于0") } if c.MonitorConfig.AlertThresholds.OrderFailureRate < 0 || c.MonitorConfig.AlertThresholds.OrderFailureRate > 100 { return fmt.Errorf("订单失败率阈值必须在0-100之间") } if c.MonitorConfig.AlertThresholds.MemoryUsageThreshold < 0 || c.MonitorConfig.AlertThresholds.MemoryUsageThreshold > 100 { return fmt.Errorf("内存使用率阈值必须在0-100之间") } if c.MonitorConfig.AlertThresholds.CpuUsageThreshold < 0 || c.MonitorConfig.AlertThresholds.CpuUsageThreshold > 100 { return fmt.Errorf("CPU使用率阈值必须在0-100之间") } } return nil } // GetLockKey 生成锁键名 func (c *OptimizedConfig) GetLockKey(lockType, identifier string) string { switch lockType { case "order": return c.LockConfig.OrderLockPrefix + identifier case "position": return c.LockConfig.PositionLockPrefix + identifier case "take_profit": return c.LockConfig.TakeProfitLockPrefix + identifier default: return "unknown_lock:" + identifier } } // IsRetryableError 判断错误是否可重试 func (c *OptimizedConfig) IsRetryableError(err error) bool { if err == nil { return false } errStr := err.Error() // 定义不可重试的错误类型 nonRetryableErrors := []string{ "余额不足", "订单重复", "API-key", "无效", "权限", "签名", "参数错误", } for _, nonRetryable := range nonRetryableErrors { if contains(errStr, []string{nonRetryable}) { return false } } return true } // GetRetryDelay 计算重试延迟时间 func (c *OptimizedConfig) GetRetryDelay(attempt int) time.Duration { if attempt <= 0 { return c.RetryConfig.RetryDelay } // 指数退避算法 delay := c.RetryConfig.RetryDelay for i := 0; i < attempt; i++ { delay = time.Duration(float64(delay) * c.RetryConfig.BackoffFactor) if delay > c.RetryConfig.MaxRetryDelay { return c.RetryConfig.MaxRetryDelay } } return delay } // ShouldSync 判断是否需要同步持仓 func (c *OptimizedConfig) ShouldSync(exchangePosition, systemPosition decimal.Decimal) bool { diff := exchangePosition.Sub(systemPosition).Abs() return diff.GreaterThan(c.SyncConfig.PositionDiffThreshold) } // ShouldForceSync 判断是否需要强制同步 func (c *OptimizedConfig) ShouldForceSync(exchangePosition, systemPosition decimal.Decimal) bool { diff := exchangePosition.Sub(systemPosition).Abs() return diff.GreaterThan(c.SyncConfig.ForceSyncThreshold) } // 全局配置实例 var GlobalOptimizedConfig *OptimizedConfig // InitOptimizedConfig 初始化优化配置 func InitOptimizedConfig() error { GlobalOptimizedConfig = GetDefaultOptimizedConfig() return GlobalOptimizedConfig.ValidateConfig() } // GetOptimizedConfig 获取全局优化配置 func GetOptimizedConfig() *OptimizedConfig { if GlobalOptimizedConfig == nil { InitOptimizedConfig() } return GlobalOptimizedConfig }