-
Notifications
You must be signed in to change notification settings - Fork 76
/
mongodb.go
48 lines (39 loc) 路 1.07 KB
/
mongodb.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package mongodb
import (
"context"
"fmt"
"time"
"github.com/kamva/mgm/v3"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
_ "github.com/golang-migrate/migrate/v4/source/file"
)
const (
connectTimeout = 60 * time.Second
maxConnIdleTime = 3 * time.Minute
minPoolSize = 20
maxPoolSize = 300
)
// NewMongoDB Create new MongoDB client
func NewMongoDB(cfg *MongoDbOptions) (*mongo.Client, error) {
uriAddress := fmt.Sprintf("mongodb://%s:%s@%s:%d", cfg.User, cfg.Password, cfg.Host, cfg.Port)
opt := options.Client().ApplyURI(uriAddress).
SetConnectTimeout(connectTimeout).
SetMaxConnIdleTime(maxConnIdleTime).
SetMinPoolSize(minPoolSize).
SetMaxPoolSize(maxPoolSize)
if cfg.UseAuth {
opt = opt.SetAuth(options.Credential{Username: cfg.User, Password: cfg.Password})
}
ctx := context.Background()
client, err := mongo.Connect(ctx, opt)
if err != nil {
return nil, err
}
// setup https://github.com/Kamva/mgm
err = mgm.SetDefaultConfig(nil, cfg.Database, opt)
if err != nil {
return nil, err
}
return client, nil
}