Using the MongoDB Go Driver, how do I set up connection pooling?
Asked Answered
F

1

14

I'm using the MongoDB Go Driver in my Go (1.11) server which runs on Google Cloud's App Engine. I'm not really sure if I still manually have to set up connection pooling or if it's already being taken care of out of the box. For example I'm not entirely sure what the context (with timeout) exactly means.

My code looks like this:

package tools

import (
    "context"
    "time"
    "valuation-app/settings"

    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

// ConnectToDB starts a new database connection and returns a reference to it
func ConnectToDB() (*mongo.Database, error) {
    settings := settings.Get().Database
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    options := options.Client().ApplyURI(settings.URI)
    options.SetMaxPoolSize(10)
    client, err := mongo.Connect(ctx, options)
    if err != nil {
        return nil, err
    }

    return client.Database(settings.DatabaseName), nil
}
Feverfew answered 21/6, 2019 at 13:12 Comment(4)
The driver uses a connection pool internally.Chalet
@Chalet awesome! That's all I needed to knowFeverfew
in case you wonder where the magics happenRiesman
@Chalet comment is correct ,default is 100 (from godoc.org/go.mongodb.org/mongo-driver/mongo/…)Shult
S
7

From comments by @Alongkorn:

Mongo-go-driver takes care of connection pooling by default(100 connection by default)

You can read the source code here

Sucrose answered 7/7, 2020 at 7:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.