-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
221 lines (182 loc) · 5.07 KB
/
client.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// Package mongo
package mongo
import (
"context"
"fmt"
"reflect"
"runtime"
"time"
"github.com/assembly-hub/basics/util"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/bson/bsonoptions"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readconcern"
)
type SessionContext = mongo.SessionContext
type Client struct {
clientOptions []*options.ClientOptions
ctx context.Context
mongoClient *mongo.Client
}
func Connection(ctx context.Context, appName string, mongoConf *Conf) *Client {
if mongoConf.AuthDB == "" {
mongoConf.AuthDB = mongoConf.DB
}
if mongoConf.HostMaster == "" {
panic(fmt.Sprintf("mongotool[%s] HostMaster error", appName))
}
hosts := []string{mongoConf.HostMaster}
if mongoConf.HostSlave != "" {
hosts = append(hosts, mongoConf.HostSlave)
}
if mongoConf.DB == "" {
panic(fmt.Sprintf("mongotool[%s] db error", appName))
}
auth := ""
if mongoConf.User != "" {
auth = mongoConf.User
if mongoConf.Pass != "" {
auth += ":" + mongoConf.Pass
}
auth += "@"
}
var params []string
if mongoConf.ServerSelectionTimeoutMS <= 0 {
mongoConf.ServerSelectionTimeoutMS = 5000
}
params = append(params, fmt.Sprintf("serverSelectionTimeoutMS=%d", mongoConf.ServerSelectionTimeoutMS))
if mongoConf.ConnectTimeoutMS <= 0 {
mongoConf.ConnectTimeoutMS = 10000
}
params = append(params, fmt.Sprintf("connectTimeoutMS=%d", mongoConf.ConnectTimeoutMS))
if mongoConf.AuthMechanism == "" {
mongoConf.AuthMechanism = "SCRAM-SHA-1"
}
params = append(params, fmt.Sprintf("authMechanism=%s", mongoConf.AuthMechanism))
params = append(params, fmt.Sprintf("authSource=%s", mongoConf.AuthDB))
if mongoConf.ReplicaSet != "" {
params = append(params, fmt.Sprintf("replicaSet=%s", mongoConf.ReplicaSet))
} else {
params = append(params, "connect=direct")
}
uri := fmt.Sprintf("mongodb://%s%s/%s?%s",
auth, util.JoinArr(hosts, ","), mongoConf.DB, util.JoinArr(params, "&"))
opts := OptionsFromURI(uri)
opts.AppName = &appName
minPoolSize := uint64(5)
maxPoolSize := uint64(runtime.GOMAXPROCS(0) * 5)
opts.MinPoolSize = &minPoolSize
opts.MaxPoolSize = &maxPoolSize
client, err := NewClient(ctx, opts)
if err != nil {
panic(err)
}
if !mongoConf.Connect {
return client
}
err = client.Ping(ctx)
if err != nil {
panic(err)
}
return client
}
func NewClient(ctx context.Context, opt *ClientOptions) (*Client, error) {
if ctx == nil || opt == nil {
return nil, fmt.Errorf("ctx or opt not be nil")
}
optList := []*options.ClientOptions{opt.ClientOptions, options.Client().SetRegistry(register())}
client, err := mongo.Connect(ctx, optList...)
if err != nil {
return nil, err
}
c := new(Client)
c.clientOptions = optList
c.mongoClient = client
c.ctx = ctx
return c, nil
}
func register() *bsoncodec.Registry {
builder := bsoncodec.NewRegistryBuilder()
// 注册默认的编码和解码器
bsoncodec.DefaultValueEncoders{}.RegisterDefaultEncoders(builder)
bsoncodec.DefaultValueDecoders{}.RegisterDefaultDecoders(builder)
// 注册时间解码器
tTime := reflect.TypeOf(time.Time{})
tCodec := bsoncodec.NewTimeCodec(bsonoptions.TimeCodec().SetUseLocalTimeZone(true))
registry := builder.RegisterTypeDecoder(tTime, tCodec).Build()
return registry
}
func (c *Client) Ping(ctx context.Context) error {
ctxObj := c.ctx
if ctx != nil {
ctxObj = ctx
}
err := c.mongoClient.Ping(ctxObj, nil)
if err != nil {
return err
}
return nil
}
func (c *Client) Ctx() context.Context {
return c.ctx
}
// NewSession
// 要求mongo 版本 4.0起
// 需要mongo副本集群
func (c *Client) NewSession(fn func(sessionCtx SessionContext) error) error {
// session
sessionOpts := options.Session().SetDefaultReadConcern(readconcern.Majority())
session, err := c.mongoClient.StartSession(sessionOpts)
if err != nil {
return err
}
defer session.EndSession(context.Background())
// transaction
err = mongo.WithSession(c.ctx, session, func(sessionCtx SessionContext) (err error) {
defer func() {
if p := recover(); p != nil {
errTx := session.AbortTransaction(context.Background())
err = fmt.Errorf("%v, Transaction: %w", p, errTx)
}
}()
if err = session.StartTransaction(); err != nil {
return err
}
err = fn(sessionCtx)
if err != nil {
err2 := session.AbortTransaction(context.Background())
if err2 != nil {
return fmt.Errorf("%w, %v", err2, err)
}
return err
}
return session.CommitTransaction(context.Background())
})
if err != nil {
return err
}
return nil
}
func (c *Client) Database(dbName string) *Database {
db := new(Database)
db.Client = c
db.dbName = dbName
db.db = c.mongoClient.Database(dbName)
return db
}
func (c *Client) TryDatabase(dbName string) (db *Database, exist bool, err error) {
names, err := c.mongoClient.ListDatabaseNames(c.ctx, map[string]string{"name": dbName})
if err != nil {
return nil, false, err
}
exist = false
if len(names) > 0 {
exist = true
}
db = new(Database)
db.Client = c
db.dbName = dbName
db.db = c.mongoClient.Database(dbName)
return db, exist, nil
}