Golang, mgo and a persistent connection...

polaris · 2017-09-06 06:00:23 · 682 次点击    
这是一个分享于 2017-09-06 06:00:23 的资源,其中的信息可能已经有所发展或是发生改变。

Hi, Can anyone to help with an easy question by Golang/mgo? I want to rewrite of my newbie-code at Go for optimize an interaction between an easy HTTP-router and MongoDB engine. At now, the function for getting an propertie of object create a connection to the database at every time at calling. I have no to loosing by performance, because my router to serve of one hundred client per a hour (joke) :smile: But I want to clean up MongoDB log from excess records und level up of my Golang skill too :smile: Whta I need to add at the next code for optimize it?

func urlinfo (c Settings, u string) (r *Ro) {
Host := []string{
    c.Mgo_host,
}
session, err := mgo.DialWithInfo(&mgo.DialInfo{
    Addrs: Host,
    Username: c.Mgo_user,
    Password: c.Mgo_pass,
    Database: c.Mgo_audb,
})
if err != nil {
    fmt.Println("Could not to connect to MongoDB engine!")
    return
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)

c := session.DB(c.Mgo_iodb).C("rtab")

clRo := new(Ro)
err = c.Find(bson.M{"id": u}).Select(bson.M{"id": &clRo.Id, "acl": &clRo.Acl, "tZ": &clRo.TZ }).One(&clRo)
return clRo
}  

**评论:**

fmpwizard:

Hi,

First, in Go, you don't normally named a variable Mgo_user, instead you would use MGOUser or MgoUser, no underscores in names.

Now, I don't know how you call urlinfo from your router, but, seeing that you are passing a Settings struct, I would instead pass a mongo session already initiated from main(). That way, you only start one session to mongodb, mgo will create a pool of connections to use, and then each handler will reuse those connections instead of starting a new one for each http request.

Hope that helps.


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

682 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传