Skip to content

Commit 2843ee8

Browse files
author
hero
committed
mgo官方库添加事务(不能在单节点)处理
1 parent c535be8 commit 2843ee8

File tree

1 file changed

+5
-4
lines changed

1 file changed

+5
-4
lines changed

mongodb/mongo-go-driver/main.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ func TestMongo(url string) {
6161
if client, err = mongo.Connect(getContext(), opt); err != nil {
6262
checkErr(err)
6363
}
64-
//StudySession(client)
64+
//UseSession(client)
6565
//判断服务是否可用
6666
if err = client.Ping(getContext(), readpref.Primary()); err != nil {
6767
checkErr(err)
@@ -178,7 +178,8 @@ func TestMongo(url string) {
178178

179179
}
180180

181-
func StudySession(client *mongo.Client) {
181+
//不能在单节点使用(副本集可以使用)
182+
func UseSession(client *mongo.Client) {
182183
client.UseSession(getContext(), func(sctx mongo.SessionContext) error {
183184
err := sctx.StartTransaction(options.Transaction().
184185
SetReadConcern(readconcern.Snapshot()).
@@ -187,12 +188,12 @@ func StudySession(client *mongo.Client) {
187188
if err != nil {
188189
return err
189190
}
190-
_, err = client.Database("aa").Collection("bb").UpdateOne(sctx, bson.D{{"aa", "1"}}, bson.D{{"$set", bson.D{{"status", "123123"}}}})
191+
_, err = client.Database("aa").Collection("bb").InsertOne(sctx, bson.D{{"aa", 3}})
191192
if err != nil {
192193
_ = sctx.AbortTransaction(sctx)
193194
return err
194195
}
195-
_, err = client.Database("cc").Collection("dd").InsertOne(sctx, bson.D{{"employee", 3}})
196+
_, err = client.Database("aa").Collection("bb").InsertOne(sctx, bson.D{{"bb", 3}})
196197
if err != nil {
197198
_ = sctx.AbortTransaction(sctx)
198199
return err

0 commit comments

Comments
 (0)