1

我在项目中有两个 go 文件

  1. 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
}

  1. 查询.go

然后该文件定义数据库,然后对其进行查询

client := GetMongoDBClient()

collection := client.Database("demo").Collection("user")

err := collection.FindOne(context.TODO(), filter).Decode(&user)

当我发出 200 个请求时,我收到了来自 Atlas 的电子邮件,说我已经超过了 80 个连接限制配额。如何在这里使用连接池?

4

2 回答 2

2

您是否尝试过 MaxPoolSize 选项:

clientOptions = clientOptions.SetMaxPoolSize(50)

我没有在官方的 mongo 驱动程序中尝试过这个,但是 mgo 驱动程序有一个类似的选项,可以按预期工作。

于 2019-10-14T03:05:45.783 回答
0

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

于 2020-06-02T21:17:29.633 回答