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?
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 useMGOUser
orMgoUser
, no underscores in names.Now, I don't know how you call
urlinfo
from your router, but, seeing that you are passing aSettings
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.
