Golang, mgo and a persistent connection...

polaris · · 476 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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(&amp;mgo.DialInfo{ Addrs: Host, Username: c.Mgo_user, Password: c.Mgo_pass, Database: c.Mgo_audb, }) if err != nil { fmt.Println(&#34;Could not to connect to MongoDB engine!&#34;) return } defer session.Close() session.SetMode(mgo.Monotonic, true) c := session.DB(c.Mgo_iodb).C(&#34;rtab&#34;) clRo := new(Ro) err = c.Find(bson.M{&#34;id&#34;: u}).Select(bson.M{&#34;id&#34;: &amp;clRo.Id, &#34;acl&#34;: &amp;clRo.Acl, &#34;tZ&#34;: &amp;clRo.TZ }).One(&amp;clRo) return clRo } </code></pre> <hr/>**评论:**<br/><br/>fmpwizard: <pre><p>Hi,</p> <p>First, in Go, you don&#39;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&#39;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

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