问题:
Mongo 聚合查询大约需要花费大约500-650 毫秒返回,尽管使用mgo.
示例查询:
func (r userRepo) GetUserByID(id string) (User, error) { info, err := db.Info() if err != nil { log.Fatal(err) } session, err := mgo.Dial(info.ConnectionString()) if err != nil { log.Fatal(err) } defer session.Close() var user User c := session.DB(info.Db()).C("users") o1 := bson.M{"$match": bson.M{"_id": id}} o2 := bson.M{"$project": bson.M{ "first": "$first", "last": "$last", "email": "$email", "fb_id": "$fb_id", "groups": "$groups", "fulfillments": "$fulfillments", "denied_requests": "$denied_requests", "invites": "$invites", "requests": bson.M{ "$filter": bson.M{ "input": "$requests", "as": "item", "cond": bson.M{ "$eq": []interface{}{"$$item.active", true}, }, }, }, }} pipeline := []bson.M{o1, o2} err = c.Pipe(pipeline).One(&user) if err != nil { return user, err } return user, nil }
问题:查询性能缓慢是否有明显的原因?
提示: mgo.Dial() 方法在每个之前被调用
回答:
是的,性能缓慢可归因于重复调用 mgo.Dial()。这种方法每次都会与MongoDB服务器建立连接,可能需要几百毫秒的时间。要解决此问题,请创建一个全局会话变量,在启动时建立一次连接(例如,在包 init() 函数中),然后使用该会话(或其副本)进行所有查询。
解决方案:
var session *mgo.Session var info *db.Inf // Use your type here func init() { var err error if info, err = db.Info(); err != nil { log.Fatal(err) } if session, err = mgo.Dial(info.ConnectionString()); err != nil { log.Fatal(err) } } func (r userRepo) GetUserByID(id string) (User, error) { sess := session.Clone() defer sess.Close() var user User c := sess.DB(info.Db()).C("users") o1 := bson.M{"$match": bson.M{"_id": id}} o2 := bson.M{"$project": bson.M{ "first": "$first", "last": "$last", "email": "$email", "fb_id": "$fb_id", "groups": "$groups", "fulfillments": "$fulfillments", "denied_requests": "$denied_requests", "invites": "$invites", "requests": bson.M{ "$filter": bson.M{ "input": "$requests", "as": "item", "cond": bson.M{ "$eq": []interface{}{"$$item.active", true}, }, }, }, }} pipeline := []bson.M{o1, o2} err = c.Pipe(pipeline).One(&user) if err != nil { return user, err } return user, nil }
以上是为什么我的 mgo 查询需要 500-650 毫秒才能执行?的详细内容。更多信息请关注PHP中文网其他相关文章!