Brak opisu
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.

mongodb_config.go 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 time.Duration `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. // Load 从YAML数据加载配置
  33. func (c *MongoDBConfig) Load(data map[string]interface{}) error {
  34. return c.LoadFromYAML(data, c)
  35. }
  36. // Validate 验证配置
  37. func (c *MongoDBConfig) Validate() error {
  38. if c.URI == "" {
  39. return fmt.Errorf("mongodb URI must be configured")
  40. }
  41. if c.Database == "" {
  42. return fmt.Errorf("mongodb database name must be configured")
  43. }
  44. if c.MaxPoolSize < c.MinPoolSize {
  45. return fmt.Errorf("maxPoolSize must be greater than or equal to minPoolSize")
  46. }
  47. if c.Timeout <= 0 {
  48. return fmt.Errorf("timeout must be a positive integer")
  49. }
  50. return nil
  51. }
  52. // IsConfigured 检查是否已配置
  53. func (c *MongoDBConfig) IsConfigured() bool {
  54. return c.URI != "" && c.Database != ""
  55. }
  56. // 自动注册
  57. func init() {
  58. Register("mongodb", &MongoDBConfig{})
  59. }