| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- package subconfigs
-
- import (
- "fmt"
- "time"
- )
-
- // MongoDBConfig MongoDB客户端配置
- type MongoDBConfig struct {
- BaseConfig
- URI string `yaml:"uri"` // MongoDB连接URI,如:"mongodb://localhost:27017"
- Database string `yaml:"database"` // 默认数据库名
- Username string `yaml:"username"` // 用户名(可选)
- Password string `yaml:"password"` // 密码(可选)
- AuthSource string `yaml:"authSource"` // 认证数据库,默认:"admin"
- MaxPoolSize uint64 `yaml:"maxPoolSize"` // 最大连接池大小
- MinPoolSize uint64 `yaml:"minPoolSize"` // 最小连接池大小
- SSL bool `yaml:"ssl"` // 是否使用SSL连接
- Timeout time.Duration `yaml:"timeout"` // 连接超时时间(毫秒)
- }
-
- // 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
- }
-
- // 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() {
- Register("mongodb", &MongoDBConfig{})
- }
|