【问题标题】:MongoDB connection pool in Golang official driverGolang官方驱动中的MongoDB连接池
【发布时间】:2019-10-14 02:47:58
【问题描述】:

我在项目中有两个 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. query.go

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

client := GetMongoDBClient()

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

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

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

【问题讨论】:

    标签: mongodb go mongo-go


    【解决方案1】:

    您是否尝试过 MaxPoolSize 选项:

    clientOptions = clientOptions.SetMaxPoolSize(50)
    

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

    【讨论】:

      【解决方案2】:

      REM** 默认 poolSize 为 100 见Golang driver docs

      【讨论】:

      • 仅包含链接的答案将在未来被删除,因此请附上代码及其解释。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-20
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多