Best practice to maintain a mgo session

后端 未结 3 1011
感动是毒
感动是毒 2020-11-27 14:03

I\'m currently using a mongodb with mgo lib for a web application, but I\'m not sure if the way I\'m using it, is good one ..

package db

import (
    \"gopk         


        
3条回答
  •  孤独总比滥情好
    2020-11-27 14:43

    Although not directly answering your question, regarding mgo session checking you must use defer/recover since mgo calls (even mgo.session.Ping) panic. As far as I can tell there is no other way of checking mgo session state (mgo godocs). You can use Gustavo Niemeyer's suggestion and add a method on your DataStore type.

    func (d *DataStore) EnsureConnected() {
        defer func() {
            if r := recover(); r != nil {
                //Your reconnect logic here.
            }
        }()
    
        //Ping panics if session is closed. (see mgo.Session.Panic())  
        d.Ping()
    }
    

提交回复
热议问题