这种情况可能是由于 MongoDB 驱动程序默认的连接超时时间比较短所导致的。在 Golang 中,你可以通过设置 SetMaxTime()
方法来指定操作的最大执行时间,确保不会在规定时间内中断事务。
下面是一个示例代码片段,展示如何使用 context.WithTimeout()
来设置操作的超时时间为 5 分钟:
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
panic(err)
}
defer client.Disconnect(ctx)
collection := client.Database("mydb").Collection("mycollection")
opts := options.Transaction().SetMaxCommitTime(5 * time.Minute)
session, err := client.StartSession()
if err != nil {
panic(err)
}
defer session.EndSession(ctx)
err = mongo.WithSession(ctx, session, func(sessionContext mongo.SessionContext) error {
return session.StartTransaction(opts).
AddOperation(mongo.InsertOne{
Document: bson.M{"key": "value"},
}).
AddOperation(mongo.UpdateOne{
Filter: bson.M{"key": "value"},
Update: bson.M{"$set": bson.M{"key2": "value2"}},
}).
CommitTransaction(sessionContext)
})
if err != nil {
panic(err)
}
}
通过上述代码,你可以将操作超时时间设置为 5 分钟,确保事务不会在 2 分钟内被中断。请根据实际需要调整代码中的连接字符串和操作逻辑。
内容由零声教学AI助手提供,问题来源于学员提问