插入第一个元素时为什么 collection.InsertOne 的速度较慢?
时间:2024-03-20
浏览:185
作者:佚名
在使用 Go 的官方 MongoDB 驱动程序时,首次调用 collection.InsertOne 会出现明显延迟,而后续调用则非常迅速。这是因为该驱动程序使用延迟连接,首次调用时需要建立连接。可以通过使用 context.WithTimeout 强制连接来避免这种延迟。
问题内容
我正在测试 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:
ctx, _ = context.WithTimeout(context.Background(), 2*time.Second) err = client.Ping(ctx, readpref.Primary())
这将强制连接并消除第一次插入时的插入延迟。
今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
站内热门
最新文章
热门专题
