Concurrency in gopkg.in/mgo.v2 (Mongo, Go)

I want to use MongoDB in a webapp written in Go.

Is it possible to use one mgo.Session and use it simultaneously in a web application. e.g. in http.Handler

or should I call Session.Copy and Session.Close create a session pool.

It sounds contradictory, somewhere I read that the pool is already implemented inside mgo.Session , and I can use the session at the same time, and in other places I read that I need Copy and Close .

+7
mongodb go mgo
source share
2 answers

mgo.Session is safe to use at the same time. Quote from the document:

All concurrency session methods are safe and can be called from multiple goroutines.

But this does not mean that you should not create and use more of them in parallel by calling Session.Copy() or Session.Clone() , in the initial session received during dialing.

To be concurrency - safe and take advantage of using more of them, are not mutually exclusive (they are not mutually exclusive). Although you can use a single mgo.Session from an arbitrary number of goroutines that will not scale well, it will not scale at all. Sessions automatically manage the connection pool, possibly even for multiple server nodes, but if you use one Session , you do not use it. By creating a new Session at the beginning of each of your requests (if necessary) and closing it correctly at the end ( Session.Close() , preferably called using defer ), you use the potential use of several connections at the same time, possibly on several servers (if any) and therefore it is better to use server resources; and getting faster response times (both from the database and ultimately to your end-users HTTP). Calling Session.Close() does not close the basic connection to the server, it will simply return the connection back to the pool, ready to pick up another session.

Also see the related question about using Session s: Performance of mgo requests looks consistently slow (500-650 ms)

+5
source share

Calling Dial or DialWithTimeout or DialWithInfo establish a connection pool. If you need more than one session, you need to call session.Copy () or session.New (), session.Copy () is preferred since it will save auth. Here is an example:

Suppose you have a UserService structure to handle all of your db user needs. Please note that this is from the top of the head, so there may be some syntax errors, but there is an idea.

 type Userservice struct { DB *mgo.Session } func (s *Userservice) Create(u *User) error { sessionCopy := s.DB.Copy() defer sessionCopy.Close() db := sessionCopy.DB("test_db") col := db.C("users") if err := col.Insert(u); err != nil { return err } } 
+2
source share

All Articles