go-bongo / bongo

Go ODM for MongoDB
MIT License
487 stars 40 forks source link

Should Clone() replace with Copy() ? #32

Open miffa opened 6 years ago

miffa commented 6 years ago
var err error
sess := c.Connection.Session.Clone()       // if  mongo cluster has a failover, sess socket may be closed,  **Should Clone() replace with Copy()** ?
                                                                     //otherwise I  have to call sess.Refresh()
defer sess.Close()
miffa commented 5 years ago

mgo driver works like this:

  • session = mgo.Dial(); defer session.Close()
  • In another package, session.Clone() to have a copy of the session.
  • In a handler or repo, session.Copy() the cloned session and defer session.Close()

This ensures that should the mongodb server connection go away and return later you'll still be able to connect to the mongo server.

Where is the reference in your question?

Can you be more detailed?

If use Clone() session access HA mongo and then mongo has been switched between master and slave, your session has already been closed by mongo, your operation will fail. If use Copy() session, the function will check sessions pool whether valid and give you a healthy session. This is my usage scenario~