Golang官方驱动程序中的MongoDB连接池



我在项目中有两个go文件

  1. 主去

此文件创建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
}
  1. 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 驱动程序有一个类似的选项,可以按预期工作。

REM** 默认池大小为 100 请参阅 Golang 驱动程序文档

最新更新