|
First I run mongo 2.6.12 with docker:
docker run -p 27018:27017 --name mongo26 -d mongo:2.6
|
Then, I run this code to test connections, which set `SetMaxPoolSize(1)` to keep connection pool only one connection:
package main
|
|
import (
|
"context"
|
"math/rand"
|
"sync"
|
"time"
|
|
"go.mongodb.org/mongo-driver/bson"
|
"go.mongodb.org/mongo-driver/mongo"
|
"go.mongodb.org/mongo-driver/mongo/options"
|
)
|
|
|
func main() {
|
opts := options.Client().
|
ApplyURI("mongodb://127.0.0.1:27018").
|
SetMaxPoolSize(uint64(1))
|
client, err := mongo.NewClient(opts)
|
if err != nil {
|
panic(err)
|
}
|
|
if err := client.Connect(context.Background()); err != nil {
|
panic(err)
|
}
|
|
var wg = &sync.WaitGroup{}
|
for i := 0; i < 10; i++ {
|
wg.Add(1)
|
go queryData(client, wg)
|
}
|
wg.Wait()
|
}
|
|
func queryData(cli *mongo.Client, wg *sync.WaitGroup) {
|
defer wg.Done()
|
var coll = cli.Database("test").Collection("test")
|
for i := 0; i < 1000000; i++ {
|
coll.FindOne(context.Background(), bson.M{})
|
time.Sleep(time.Nanosecond * time.Duration(rand.Intn(1000)))
|
}
|
}
|
While code is runing, check the connection between application and mongodb, there are 3 connections, which 2 greater than expected 1.
ss -antp | grep 27018 | grep test
|
ESTAB 0 0 127.0.0.1:38932 127.0.0.1:27018 users:(("test",pid=764058,fd=7))
|
ESTAB 0 0 127.0.0.1:38930 127.0.0.1:27018 users:(("test",pid=764058,fd=6))
|
ESTAB 0 43 127.0.0.1:38938 127.0.0.1:27018 users:(("test",pid=764058,fd=8))
|
Change the code to set connection pool size to 2 with :`SetMaxPoolSize(2)`,run the code again and check the connections:
ss -antp | grep 27018 | grep test
|
ESTAB 0 0 127.0.0.1:38956 127.0.0.1:27018 users:(("test",pid=764331,fd=7))
|
ESTAB 0 0 127.0.0.1:38954 127.0.0.1:27018 users:(("test",pid=764331,fd=6))
|
ESTAB 0 43 127.0.0.1:38962 127.0.0.1:27018 users:(("test",pid=764331,fd=8))
|
ESTAB 0 43 127.0.0.1:38966 127.0.0.1:27018 users:(("test",pid=764331,fd=9))
|
It's 4, also 2 greater than expected 2.
|