mongo.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package mongo
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "go.mongodb.org/mongo-driver/mongo"
  7. "go.mongodb.org/mongo-driver/mongo/options"
  8. "go.mongodb.org/mongo-driver/mongo/readpref"
  9. )
  10. // Config MongoDB配置
  11. type Config struct {
  12. URI string `mapstructure:"uri"`
  13. Database string `mapstructure:"database"`
  14. Timeout time.Duration `mapstructure:"timeout"`
  15. MaxPoolSize uint64 `mapstructure:"max_pool_size"`
  16. }
  17. // MongoDB连接管理器
  18. type MongoDB struct {
  19. config *Config
  20. client *mongo.Client
  21. database *mongo.Database
  22. }
  23. // New 创建新的MongoDB客户端
  24. func New(config *Config) (*MongoDB, error) {
  25. ctx, cancel := context.WithTimeout(context.Background(), config.Timeout)
  26. defer cancel()
  27. // 创建MongoDB客户端选项
  28. clientOptions := options.Client().
  29. ApplyURI(config.URI).
  30. SetMaxPoolSize(config.MaxPoolSize)
  31. // 连接到MongoDB
  32. client, err := mongo.Connect(ctx, clientOptions)
  33. if err != nil {
  34. return nil, fmt.Errorf("连接MongoDB失败: %w", err)
  35. }
  36. // 验证连接
  37. if err := client.Ping(ctx, readpref.Primary()); err != nil {
  38. return nil, fmt.Errorf("MongoDB连接测试失败: %w", err)
  39. }
  40. // 获取数据库
  41. database := client.Database(config.Database)
  42. return &MongoDB{
  43. config: config,
  44. client: client,
  45. database: database,
  46. }, nil
  47. }
  48. // Close 关闭MongoDB连接
  49. func (m *MongoDB) Close() error {
  50. ctx, cancel := context.WithTimeout(context.Background(), m.config.Timeout)
  51. defer cancel()
  52. return m.client.Disconnect(ctx)
  53. }
  54. // GetDatabase 获取数据库实例
  55. func (m *MongoDB) GetDatabase() *mongo.Database {
  56. return m.database
  57. }
  58. // GetCollection 获取集合实例
  59. func (m *MongoDB) GetCollection(name string) *mongo.Collection {
  60. return m.database.Collection(name)
  61. }
  62. // Client 获取原始MongoDB客户端
  63. func (m *MongoDB) Client() *mongo.Client {
  64. return m.client
  65. }