// subconfigs/service_config.go package subconfigs import ( "fmt" "log" ) type ServicesConfig struct { BaseConfig AppName string `yaml:"app_name"` //当前应用名称 AppVersion string `yaml:"app_version"` //当前应用版本 AppEnv string `yaml:"app_env"` //环境参数 dev test prod AppAuthToken string `yaml:"app_auth_token"` //使用静态认证的时候使用的token Services map[string]*ServiceConfig `yaml:"services"` //多个服务配置项 } // DatabaseConfig 数据库配置 type ServiceConfig struct { BaseConfig Port int `yaml:"port"` ServiceName string `yaml:"service_name"` InstanceName string `yaml:"instance_name"` ReadTimeout int `yaml:"read_timeout"` WriteTimeout int `yaml:"write_timeout"` IdleTimeout int `yaml:"idle_timeout"` } // SetDefaults 设置默认值 - 实现 ConfigLoader 接口 func (c *ServicesConfig) SetDefaults() { if c.AppEnv == "" { c.AppEnv = "dev" } //因为是多集合,外层调这里赋默认值,这个时候对象还没有建立。赋默认值的地方移到其他地方去 } func (c *ServicesConfig) Load(data map[string]interface{}) error { // 初始化 c.Services = make(map[string]*ServiceConfig) // 遍历所有配置 for dbName, dbData := range data { dbDataMap, ok := dbData.(map[interface{}]interface{}) if !ok { return fmt.Errorf("service '%s' config is not a map", dbName) } // 转换为 map[string]interface{} stringMap := make(map[string]interface{}) for k, v := range dbDataMap { if key, ok := k.(string); ok { stringMap[key] = v } } // 创建 ServiceConfig 对象并设置默认值 dbConfig := &ServiceConfig{} dbConfig.SetDefaults() // 先设置默认值 // 加载单个服务配置 if err := dbConfig.Load(stringMap); err != nil { return fmt.Errorf("failed to load servuce '%s' config: %v", dbName, err) } c.Services[dbName] = dbConfig } // 设置默认值和验证 //c.SetDefaults() return c.Validate() } // SetDefaults 设置默认值 - 实现 ConfigLoader 接口 func (c *ServiceConfig) SetDefaults() { if c.Port == 0 { c.Port = 8080 } if c.IdleTimeout == 0 { c.IdleTimeout = 60 } if c.ReadTimeout == 0 { c.ReadTimeout = 30 } if c.WriteTimeout == 0 { c.WriteTimeout = 30 } } // Load 从yaml数据加载 - 实现 ConfigLoader 接口 func (c *ServiceConfig) Load(data map[string]interface{}) error { // 虽然可能不会被直接调用,但为了接口完整性还是要实现 return c.LoadFromYAML(data, c) } // ========== 业务方法 ========== // Validate 验证配置(数据库配置) func (c *ServiceConfig) Validate() error { if c.Port <= 0 || c.Port > 65535 { return fmt.Errorf("invalid service port: %d", c.Port) } return nil } // Validate 验证配置(多数据库配置) func (c *ServicesConfig) Validate() error { if c.Services == nil { log.Println("❌ 错误: 未找到任何微服务配置,请检查配置文件中的 'services' 配置") return fmt.Errorf("no services configurations found") } // 必须要有默认数据库 if _, exists := c.Services["default"]; !exists { availableDBs := c.GetAllServiceNames() log.Printf("❌ 错误: 默认微服务配置未找到。可用的微服务配置: %v。请在配置文件中添加 'default' 微服务", availableDBs) return fmt.Errorf("default service not found") } // 验证每个数据库配置 for name, db := range c.Services { if db == nil { log.Printf("❌ 错误: 微服务 '%s' 配置为空", name) return fmt.Errorf("service '%s' configuration is nil", name) } if err := db.Validate(); err != nil { log.Printf("❌ 错误: 微服务 '%s' 验证失败: %v", name, err) return fmt.Errorf("service '%s' validation failed: %v", name, err) } } log.Printf("✅ 微服务配置验证通过,找到 %d 个微服务配置", len(c.Services)) return nil } // IsConfigured 判断是否已配置(数据库配置) func (c *ServiceConfig) IsConfigured() bool { if c.Port <= 0 { log.Println("⚠️ 警告: 微服务 Port 未配置或无效") return false } return true } // IsConfigured 判断是否已配置(多数据库配置) func (c *ServicesConfig) IsConfigured() bool { defaultDB := c.GetDefaultService() if defaultDB == nil { log.Println("❌ 错误: 默认微服务不存在") return false } if !defaultDB.IsConfigured() { log.Println("❌ 错误: 默认微服务配置不完整") return false } return true } // GetDefaultService 获取默认微服务(必须存在) func (c *ServicesConfig) GetDefaultService() *ServiceConfig { if c.Services == nil { log.Println("❌ 错误: 尝试获取默认微服务时,微服务配置为空") return nil } if db, exists := c.Services["default"]; exists { return db } // 如果没有名为default的,尝试返回第一个(但会记录警告) for name, db := range c.Services { log.Printf("⚠️ 警告: 未找到名为 'default' 的微服务,使用第一个微服务 '%s' 作为默认", name) return db } log.Println("❌ 错误: 服务模块配置中没有任何配置") return nil } // GetService 按名称获取微服务(为空时记录错误) func (c *ServicesConfig) GetService(name string) *ServiceConfig { if c.Services == nil { log.Printf("❌ 错误: 尝试获取微服务 '%s' 时,微服务配置为空", name) return nil } db := c.Services[name] if db == nil { availableDBs := c.GetAllServiceNames() log.Printf("❌ 错误: 微服务 '%s' 不存在。可用的微服务: %v", name, availableDBs) } return db } // GetAllServiceNames 获取所有数据库名称 func (c *ServicesConfig) GetAllServiceNames() []string { if c.Services == nil { log.Println("⚠️ 警告: 尝试获取微服务配置节点名称时,微服务配置为空") return []string{} } names := make([]string, 0, len(c.Services)) for name := range c.Services { names = append(names, name) } return names } // GetServiceNamesWithoutDefault 获取除default外的所有微服务配置节点名称 func (c *ServicesConfig) GetServiceNamesWithoutDefault() []string { if c.Services == nil { return []string{} } names := make([]string, 0, len(c.Services)-1) for name := range c.Services { if name != "default" { names = append(names, name) } } return names } // 自动注册 func init() { Register("services", &ServicesConfig{}) }