我的项目中有两个go文件
- main.go
此文件创建 http 服务器和 mongoDB 连接以及允许使用以下重用连接的方法
func ConnectMongoDB() {
ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
// user Connection database
// Set client options
clientOptions := options.Client().ApplyURI("mongodb+srv://localhost:27017/demo")
// Connect to MongoDB
userclient, err = mongo.Connect(ctx, clientOptions)
if err != nil {
log.Fatal(err)
}
// Check the connection
err = userclient.Ping(ctx, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to user MongoDB!")
}
//GetMongoDBClient , return mongo client for CRUD operations
func GetMongoDBClient() *mongo.Client {
return userclient
}
- query.go
该文件然后定义数据库,然后对其进行查询
client := GetMongoDBClient()
collection := client.Database("demo").Collection("user")
err := collection.FindOne(context.TODO(), filter).Decode(&user)
当我发出 200 个请求时,我收到来自 Atlas 的电子邮件,说我已经超出了 80 个连接限制配额。这里如何利用连接池?
最佳答案
您是否尝试过 MaxPoolSize 选项:
clientOptions = clientOptions.SetMaxPoolSize(50)
我还没有在官方 mongo 驱动程序中尝试过此操作,但 mgo 驱动程序有一个类似的选项,可以按预期工作。
关于Golang官方驱动中的MongoDB连接池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58369504/