globalsign / mgo

The MongoDB driver for Go
Other
1.97k stars 230 forks source link

best way to work with connection pool #339

Closed mattheusv closed 5 years ago

mattheusv commented 5 years ago

How is the bet way to work with connection pool with mgo? Currently i'm woorking using session.New(), and after I close this with session.Close()

But when I open more than 4096 session with session.New(), I can not open more sesssion, I get the next debug message: Per-server connection limit reached. Seems like that I not closing sessions, but always that I return a new session with session.New(), I close them with session.Close().


What version of MongoDB are you using (mongod --version)?

4.0.6

What version of Go are you using (go version)?

Go 1.11

What operating system and processor architecture are you using (go env)?

Windows server
mattheusv commented 5 years ago

Here is simple example

var (
    sessionDB *mgo.Session
)

type MongoCfg struct {
    User     string
    Password string
    Source   string
    Host     string
    Port     int
    Database string
}

func GetSession() (*mgo.Session, error) {
    if sessionDB != nil {
        logrus.Debug("opening new session with database")
        return sessionDB.New(), nil
    }
    return nil, errors.New("database not connected")
}

func LoadDBConnection(mongoCfg MongoCfg) error {
    url := fmt.Sprintf("%s:%d", mongoCfg.Host, mongoCfg.Port)
    session, err := mgo.DialWithInfo(&mgo.DialInfo{
        Timeout:  time.Duration(15 * time.Second),
        Database: mongoCfg.Database,
        Username: mongoCfg.User,
        Password: mongoCfg.Password,
        Source:   mongoCfg.Source,
        Addrs:    []string{url},
    })
    if err != nil {
        return err
    }
    sessionDB = session
    return nil
}

I'm use always the func GetSession() when I need to interact with mongodb