<p>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) :) But I want to clean up MongoDB log from excess records und level up of my Golang skill too :)
Whta I need to add at the next code for optimize it?</p>
<pre><code>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
}
</code></pre>
<hr/>**评论:**<br/><br/>fmpwizard: <pre><p>Hi,</p>
<p>First, in Go, you don't normally named a variable <code>Mgo_user</code>, instead you would use <code>MGOUser</code> or <code>MgoUser</code>, no underscores in names.</p>
<p>Now, I don't know how you call <code>urlinfo</code> from your router, but, seeing that you are passing a <code>Settings</code> 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.</p>
<p>Hope that helps.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传