在使用 Golang 操作 MongoDB 时,你可以通过设置会话(session)的最大超时时间来控制事务的超时。下面是一个示例代码:
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"time"
)
func main() {
client, err := mongo.Connect(context.Background(), options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
fmt.Println("Failed to connect to MongoDB:", err)
return
}
session, err := client.StartSession(options.Session().SetMaxCommitTime(5 * time.Second))
if err != nil {
fmt.Println("Failed to start session:", err)
return
}
defer session.EndSession(context.Background())
collection := client.Database("your_database").Collection("your_collection")
err = mongo.WithSession(context.Background(), session, func(sessionContext mongo.SessionContext) error {
// 在此处执行事务操作
return nil
})
if err != nil {
fmt.Println("Transaction failed:", err)
} else {
fmt.Println("Transaction successful")
}
}
在上述代码中,SetMaxCommitTime
方法用于设置事务的最大超时时间,这里将其设置为 5 秒。你可以根据需要调整该值。
请确保你已经安装了 "go.mongodb.org/mongo-driver/mongo"
包,并根据实际情况修改数据库连接 URI、数据库名称和集合名称等信息。
内容由零声教学AI助手提供,问题来源于学员提问