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