-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo_transaction.go
74 lines (62 loc) · 1.48 KB
/
mongo_transaction.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
package common_utils
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
)
func ExecSession(ctx context.Context, client *mongo.Client, fn func(mongo.SessionContext) error) error {
session, err := client.StartSession()
if err != nil {
return err
}
defer session.EndSession(ctx)
// Start a transaction.
if err := session.StartTransaction(); err != nil {
return err
}
// Execute the callback with the session.
if err := mongo.WithSession(ctx, session, func(sc mongo.SessionContext) error {
if err := fn(sc); err != nil {
return err
}
return nil
}); err != nil {
return err
}
// Commit the transaction.
if err := session.CommitTransaction(ctx); err != nil {
return err
}
return nil
}
func ExecSessionWithRetry(ctx context.Context, client *mongo.Client, fn func(mongo.SessionContext) error) error {
session, err := client.StartSession()
if err != nil {
return err
}
defer session.EndSession(ctx)
// Start a transaction.
if err := session.StartTransaction(); err != nil {
return err
}
// retry 3 times
for i := 0; i < 3; i++ {
// Execute the callback with the session.
if err := mongo.WithSession(ctx, session, func(sc mongo.SessionContext) error {
if err := fn(sc); err != nil {
return err
}
return nil
}); err != nil {
if err := session.AbortTransaction(ctx); err != nil {
return err
}
continue
}
break
}
// Commit the transaction.
if err := session.CommitTransaction(ctx); err != nil {
return err
}
return nil
}