| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- 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 int `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
- }
-
- 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() {
- Register("mongodb", &MongoDBConfig{})
- }
|