package subconfigs import ( "fmt" "time" "git.x2erp.com/qdy/go-base/config/core" ) // MongoDBConfig MongoDB客户端配置 type MongoDBConfig struct { core.BaseConfig URI string `yaml:"uri" desc:"MongoDB连接URI,如:mongodb://localhost:27017"` Database string `yaml:"database" desc:"默认数据库名称"` Username string `yaml:"username" desc:"用户名(可选)"` Password string `yaml:"password" desc:"密码(可选)"` AuthSource string `yaml:"authSource" desc:"认证数据库,默认:admin"` MaxPoolSize uint64 `yaml:"maxPoolSize" desc:"最大连接池大小"` MinPoolSize uint64 `yaml:"minPoolSize" desc:"最小连接池大小"` SSL bool `yaml:"ssl" desc:"是否使用SSL连接"` Timeout int `yaml:"timeout" desc:"连接超时时间(秒)"` } func (c *MongoDBConfig) Description() string { return "MongoDB数据库连接配置" } // NewMongoDBConfig 创建MongoDB配置实例 func NewMongoDBConfig() *MongoDBConfig { return &MongoDBConfig{} } // SetDefaults 设置默认值 func (c *MongoDBConfig) SetDefaults() { c.Username = "" c.Password = "" c.MaxPoolSize = 100 c.MinPoolSize = 10 c.SSL = false c.Timeout = 30 } func (c *MongoDBConfig) GetTimeout() time.Duration { return time.Duration(c.Timeout) * time.Second } // Load 从YAML数据加载配置 func (c *MongoDBConfig) Load(data map[string]interface{}) error { return c.LoadFromYAML(data, c) } // Validate 验证配置 func (c *MongoDBConfig) Validate() error { if c.URI == "" { return fmt.Errorf("mongodb URI must be configured") } if c.Database == "" { return fmt.Errorf("mongodb database name must be configured") } if c.MaxPoolSize < c.MinPoolSize { return fmt.Errorf("maxPoolSize must be greater than or equal to minPoolSize") } if c.Timeout <= 0 { return fmt.Errorf("timeout must be a positive integer") } return nil } // IsConfigured 检查是否已配置 func (c *MongoDBConfig) IsConfigured() bool { return c.URI != "" && c.Database != "" } // 自动注册 func init() { core.Register("mongodb", &MongoDBConfig{}) }