Без опису
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package subconfigs
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. // MongoDBConfig MongoDB客户端配置
  7. type MongoDBConfig struct {
  8. BaseConfig
  9. URI string `yaml:"uri"` // MongoDB连接URI,如:"mongodb://localhost:27017"
  10. Database string `yaml:"database"` // 默认数据库名
  11. Username string `yaml:"username"` // 用户名(可选)
  12. Password string `yaml:"password"` // 密码(可选)
  13. AuthSource string `yaml:"authSource"` // 认证数据库,默认:"admin"
  14. MaxPoolSize uint64 `yaml:"maxPoolSize"` // 最大连接池大小
  15. MinPoolSize uint64 `yaml:"minPoolSize"` // 最小连接池大小
  16. SSL bool `yaml:"ssl"` // 是否使用SSL连接
  17. Timeout int `yaml:"timeout"` // 连接超时时间,单位:秒
  18. }
  19. // NewMongoDBConfig 创建MongoDB配置实例
  20. func NewMongoDBConfig() *MongoDBConfig {
  21. return &MongoDBConfig{}
  22. }
  23. // SetDefaults 设置默认值
  24. func (c *MongoDBConfig) SetDefaults() {
  25. c.Username = ""
  26. c.Password = ""
  27. c.MaxPoolSize = 100
  28. c.MinPoolSize = 10
  29. c.SSL = false
  30. c.Timeout = 30
  31. }
  32. func (c *MongoDBConfig) GetTimeout() time.Duration {
  33. return time.Duration(c.Timeout) * time.Second
  34. }
  35. // Load 从YAML数据加载配置
  36. func (c *MongoDBConfig) Load(data map[string]interface{}) error {
  37. return c.LoadFromYAML(data, c)
  38. }
  39. // Validate 验证配置
  40. func (c *MongoDBConfig) Validate() error {
  41. if c.URI == "" {
  42. return fmt.Errorf("mongodb URI must be configured")
  43. }
  44. if c.Database == "" {
  45. return fmt.Errorf("mongodb database name must be configured")
  46. }
  47. if c.MaxPoolSize < c.MinPoolSize {
  48. return fmt.Errorf("maxPoolSize must be greater than or equal to minPoolSize")
  49. }
  50. if c.Timeout <= 0 {
  51. return fmt.Errorf("timeout must be a positive integer")
  52. }
  53. return nil
  54. }
  55. // IsConfigured 检查是否已配置
  56. func (c *MongoDBConfig) IsConfigured() bool {
  57. return c.URI != "" && c.Database != ""
  58. }
  59. // 自动注册
  60. func init() {
  61. Register("mongodb", &MongoDBConfig{})
  62. }