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.
go-library/utils/dorm/mongo.go

68 lines
1.5 KiB

2 years ago
package dorm
import (
"context"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
1 year ago
// MongoClientFun *MongoClient 驱动
// string 库名
type MongoClientFun func() (*MongoClient, string)
// MongoClientCollectionFun *MongoClient 驱动
// string 库名
// string 集合
type MongoClientCollectionFun func() (*MongoClient, string, string)
// MongoClientConfig 实例配置
type MongoClientConfig struct {
2 years ago
Dns string // 地址
Opts *options.ClientOptions
2 years ago
DatabaseName string // 库名
2 years ago
}
1 year ago
// MongoClient 实例
2 years ago
type MongoClient struct {
1 year ago
db *mongo.Client // 驱动
configDatabaseName string // 库名
2 years ago
}
1 year ago
// NewMongoClient 创建实例
func NewMongoClient(config *MongoClientConfig) (*MongoClient, error) {
2 years ago
1 year ago
var ctx = context.Background()
var err error
1 year ago
c := &MongoClient{}
2 years ago
1 year ago
c.configDatabaseName = config.DatabaseName
2 years ago
2 years ago
// 连接到MongoDB
1 year ago
if config.Dns != "" {
c.db, err = mongo.Connect(ctx, options.Client().ApplyURI(config.Dns))
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
} else {
1 year ago
c.db, err = mongo.Connect(ctx, config.Opts)
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
2 years ago
}
// 检查连接
1 year ago
err = c.db.Ping(ctx, nil)
2 years ago
if err != nil {
return nil, errors.New(fmt.Sprintf("检查连接失败:%v", err))
}
return c, nil
}
// Close 关闭
1 year ago
func (c *MongoClient) Close(ctx context.Context) error {
return c.db.Disconnect(ctx)
2 years ago
}