gpt4 book ai didi

mongodb - 为什么 collection.InsertOne 在插入第一个元素时这么慢?

转载 作者:IT王子 更新时间:2023-10-29 01:40:21 26 4
gpt4 key购买 nike

我正在为 Go 测试新的官方 MongoDB 驱动程序,我注意到第一次调用 collection.InsertOne 总是花费大量时间,而所有后续调用都非常快。为什么?以及如何避免这种破坏性行为?

package main

import (
"context"
"log"
"time"

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

type Trainer struct {
Name string
Age int
City string
}

func main() {

t1 := time.Now()

// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

log.Println("Setting client options took", time.Now().Sub(t1))
t1 = time.Now()

// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}

log.Println("Connecting took", time.Now().Sub(t1))
t1 = time.Now()

// Some dummy data to add to the Database
ash := Trainer{"Ash", 30, "Pallet Town"}

// Get a handle for your collection
collection := client.Database("test").Collection("trainers")
// Insert a single document

log.Println("Getting the collection took", time.Now().Sub(t1))
t1 = time.Now()

for i := 0; i < 10; i++ {
_, err := collection.InsertOne(context.TODO(), ash)
if err != nil {
log.Fatal(err)
}
log.Println("Inserting document took", time.Now().Sub(t1))
t1 = time.Now()
}

err = client.Disconnect(context.TODO())

}

我预计所有插入操作都需要几毫秒或纳秒,而第一个大约需要 0.6 秒。这是带时间的日志:

2019/07/31 17:41:39 Setting client options took 0s
2019/07/31 17:41:39 Connecting took 0s
2019/07/31 17:41:39 Getting the collection took 0s
2019/07/31 17:41:40 Inserting document took 606.0339ms
2019/07/31 17:41:40 Inserting document took 0s
2019/07/31 17:41:40 Inserting document took 0s
2019/07/31 17:41:40 Inserting document took 0s
2019/07/31 17:41:40 Inserting document took 0s
2019/07/31 17:41:40 Inserting document took 0s
2019/07/31 17:41:40 Inserting document took 875.2µs
2019/07/31 17:41:40 Inserting document took 0s
2019/07/31 17:41:40 Inserting document took 0s
2019/07/31 17:41:40 Inserting document took 0s

最佳答案

只是为了结束评论中的问题:

MongoDB 驱动程序使用 lazy connection .查看MongoDB docs ,具体来说:

Calling Connect does not block for server discovery. If you wish to know if a MongoDB server has been found and connected to, use the Ping method:

ctx, _ = context.WithTimeout(context.Background(), 2*time.Second)
err = client.Ping(ctx, readpref.Primary())

这将强制连接并从您的第一个插入中删除插入延迟。

关于mongodb - 为什么 collection.InsertOne 在插入第一个元素时这么慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57294734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com