Geen omschrijving
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 5.9KB

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