-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo.go
84 lines (67 loc) · 1.62 KB
/
mongo.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package mongodb
import (
"context"
"github.com/boxgo/box/pkg/config"
"github.com/boxgo/box/pkg/logger"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type (
Mongo struct {
client *mongo.Client
monitor *Monitor
cfg *Config
}
)
func newMongo(cfg *Config) *Mongo {
clientOptions := options.Client()
clientOptions.ApplyURI(cfg.URI)
clientOptions.SetAppName(config.ServiceName())
if cfg.commandMonitor == nil {
cfg.commandMonitor = defaultMonitor.CommandMonitor()
}
if cfg.poolMonitor == nil {
cfg.poolMonitor = defaultMonitor.PoolEventMonitor()
}
if cfg.EnableCommandMonitor {
clientOptions.Monitor = cfg.commandMonitor
}
if cfg.EnablePoolMonitor {
clientOptions.PoolMonitor = cfg.poolMonitor
}
client, err := mongo.NewClient(clientOptions)
if err != nil {
logger.Panicf("new mongodb client error: %s", err)
}
mgo := &Mongo{
client: client,
cfg: cfg,
monitor: defaultMonitor,
}
return mgo
}
func (mgo *Mongo) Name() string {
return "mongo"
}
func (mgo *Mongo) Serve(ctx context.Context) error {
if err := mgo.client.Connect(ctx); err != nil {
return err
}
if mgo.monitor != nil {
mgo.monitor.watch(mgo.client)
}
return mgo.client.Ping(ctx, readpref.Primary())
}
func (mgo *Mongo) Shutdown(ctx context.Context) error {
if mgo.monitor != nil {
mgo.monitor.shutdown()
}
return mgo.client.Disconnect(ctx)
}
func (mgo *Mongo) Client() *mongo.Client {
return mgo.client
}
func (mgo *Mongo) DB(db string, opts ...*options.DatabaseOptions) *mongo.Database {
return mgo.client.Database(db, opts...)
}