Ei kuvausta
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

service_config.go 6.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. // subconfigs/service_config.go
  2. package subconfigs
  3. import (
  4. "fmt"
  5. "log"
  6. )
  7. type ServicesConfig struct {
  8. BaseConfig
  9. AppName string `yaml:"app_name"` //当前应用名称
  10. AppVersion string `yaml:"app_version"` //当前应用版本
  11. AppEnv string `yaml:"app_env"` //环境参数 dev test prod
  12. AppAuthToken string `yaml:"app_auth_token"` //使用静态认证的时候使用的token
  13. Services map[string]*ServiceConfig `yaml:"services"` //多个服务配置项
  14. }
  15. // DatabaseConfig 数据库配置
  16. type ServiceConfig struct {
  17. BaseConfig
  18. Port int `yaml:"port"`
  19. ServiceName string `yaml:"service_name"`
  20. InstanceName string `yaml:"instance_name"`
  21. ReadTimeout int `yaml:"read_timeout"`
  22. WriteTimeout int `yaml:"write_timeout"`
  23. IdleTimeout int `yaml:"idle_timeout"`
  24. }
  25. // SetDefaults 设置默认值 - 实现 ConfigLoader 接口
  26. func (c *ServicesConfig) SetDefaults() {
  27. if c.AppEnv == "" {
  28. c.AppEnv = "dev"
  29. }
  30. //因为是多集合,外层调这里赋默认值,这个时候对象还没有建立。赋默认值的地方移到其他地方去
  31. }
  32. func (c *ServicesConfig) Load(data map[string]interface{}) error {
  33. // 初始化
  34. c.Services = make(map[string]*ServiceConfig)
  35. // 遍历所有配置
  36. for dbName, dbData := range data {
  37. dbDataMap, ok := dbData.(map[interface{}]interface{})
  38. if !ok {
  39. return fmt.Errorf("service '%s' config is not a map", dbName)
  40. }
  41. // 转换为 map[string]interface{}
  42. stringMap := make(map[string]interface{})
  43. for k, v := range dbDataMap {
  44. if key, ok := k.(string); ok {
  45. stringMap[key] = v
  46. }
  47. }
  48. // 创建 ServiceConfig 对象并设置默认值
  49. dbConfig := &ServiceConfig{}
  50. dbConfig.SetDefaults() // 先设置默认值
  51. // 加载单个服务配置
  52. if err := dbConfig.Load(stringMap); err != nil {
  53. return fmt.Errorf("failed to load servuce '%s' config: %v", dbName, err)
  54. }
  55. c.Services[dbName] = dbConfig
  56. }
  57. // 设置默认值和验证
  58. //c.SetDefaults()
  59. return c.Validate()
  60. }
  61. // SetDefaults 设置默认值 - 实现 ConfigLoader 接口
  62. func (c *ServiceConfig) SetDefaults() {
  63. if c.Port == 0 {
  64. c.Port = 8080
  65. }
  66. if c.IdleTimeout == 0 {
  67. c.IdleTimeout = 60
  68. }
  69. if c.ReadTimeout == 0 {
  70. c.ReadTimeout = 30
  71. }
  72. if c.WriteTimeout == 0 {
  73. c.WriteTimeout = 30
  74. }
  75. }
  76. // Load 从yaml数据加载 - 实现 ConfigLoader 接口
  77. func (c *ServiceConfig) Load(data map[string]interface{}) error {
  78. // 虽然可能不会被直接调用,但为了接口完整性还是要实现
  79. return c.LoadFromYAML(data, c)
  80. }
  81. // ========== 业务方法 ==========
  82. // Validate 验证配置(数据库配置)
  83. func (c *ServiceConfig) Validate() error {
  84. if c.Port <= 0 || c.Port > 65535 {
  85. return fmt.Errorf("invalid service port: %d", c.Port)
  86. }
  87. return nil
  88. }
  89. // Validate 验证配置(多数据库配置)
  90. func (c *ServicesConfig) Validate() error {
  91. if c.Services == nil {
  92. log.Println("❌ 错误: 未找到任何微服务配置,请检查配置文件中的 'services' 配置")
  93. return fmt.Errorf("no services configurations found")
  94. }
  95. // 必须要有默认数据库
  96. if _, exists := c.Services["default"]; !exists {
  97. availableDBs := c.GetAllServiceNames()
  98. log.Printf("❌ 错误: 默认微服务配置未找到。可用的微服务配置: %v。请在配置文件中添加 'default' 微服务", availableDBs)
  99. return fmt.Errorf("default service not found")
  100. }
  101. // 验证每个数据库配置
  102. for name, db := range c.Services {
  103. if db == nil {
  104. log.Printf("❌ 错误: 微服务 '%s' 配置为空", name)
  105. return fmt.Errorf("service '%s' configuration is nil", name)
  106. }
  107. if err := db.Validate(); err != nil {
  108. log.Printf("❌ 错误: 微服务 '%s' 验证失败: %v", name, err)
  109. return fmt.Errorf("service '%s' validation failed: %v", name, err)
  110. }
  111. }
  112. log.Printf("✅ 微服务配置验证通过,找到 %d 个微服务配置", len(c.Services))
  113. return nil
  114. }
  115. // IsConfigured 判断是否已配置(数据库配置)
  116. func (c *ServiceConfig) IsConfigured() bool {
  117. if c.Port <= 0 {
  118. log.Println("⚠️ 警告: 微服务 Port 未配置或无效")
  119. return false
  120. }
  121. return true
  122. }
  123. // IsConfigured 判断是否已配置(多数据库配置)
  124. func (c *ServicesConfig) IsConfigured() bool {
  125. defaultDB := c.GetDefaultService()
  126. if defaultDB == nil {
  127. log.Println("❌ 错误: 默认微服务不存在")
  128. return false
  129. }
  130. if !defaultDB.IsConfigured() {
  131. log.Println("❌ 错误: 默认微服务配置不完整")
  132. return false
  133. }
  134. return true
  135. }
  136. // GetDefaultService 获取默认微服务(必须存在)
  137. func (c *ServicesConfig) GetDefaultService() *ServiceConfig {
  138. if c.Services == nil {
  139. log.Println("❌ 错误: 尝试获取默认微服务时,微服务配置为空")
  140. return nil
  141. }
  142. if db, exists := c.Services["default"]; exists {
  143. return db
  144. }
  145. // 如果没有名为default的,尝试返回第一个(但会记录警告)
  146. for name, db := range c.Services {
  147. log.Printf("⚠️ 警告: 未找到名为 'default' 的微服务,使用第一个微服务 '%s' 作为默认", name)
  148. return db
  149. }
  150. log.Println("❌ 错误: 服务模块配置中没有任何配置")
  151. return nil
  152. }
  153. // GetService 按名称获取微服务(为空时记录错误)
  154. func (c *ServicesConfig) GetService(name string) *ServiceConfig {
  155. if c.Services == nil {
  156. log.Printf("❌ 错误: 尝试获取微服务 '%s' 时,微服务配置为空", name)
  157. return nil
  158. }
  159. db := c.Services[name]
  160. if db == nil {
  161. availableDBs := c.GetAllServiceNames()
  162. log.Printf("❌ 错误: 微服务 '%s' 不存在。可用的微服务: %v", name, availableDBs)
  163. }
  164. return db
  165. }
  166. // GetAllServiceNames 获取所有数据库名称
  167. func (c *ServicesConfig) GetAllServiceNames() []string {
  168. if c.Services == nil {
  169. log.Println("⚠️ 警告: 尝试获取微服务配置节点名称时,微服务配置为空")
  170. return []string{}
  171. }
  172. names := make([]string, 0, len(c.Services))
  173. for name := range c.Services {
  174. names = append(names, name)
  175. }
  176. return names
  177. }
  178. // GetServiceNamesWithoutDefault 获取除default外的所有微服务配置节点名称
  179. func (c *ServicesConfig) GetServiceNamesWithoutDefault() []string {
  180. if c.Services == nil {
  181. return []string{}
  182. }
  183. names := make([]string, 0, len(c.Services)-1)
  184. for name := range c.Services {
  185. if name != "default" {
  186. names = append(names, name)
  187. }
  188. }
  189. return names
  190. }
  191. // 自动注册
  192. func init() {
  193. Register("services", &ServicesConfig{})
  194. }