I am working on a Golang SAAS application along with Mongodb. Previously I worked with db connections without pooling. As a result of this, my db hangs on or shuts down when some traffic comes in.
Then I get to know about connection pooling. I explored it but I have some doubts whether it will go with my application structure or not.
I am providing here some code samples from my application.
Function to create connection to db:
func ConnectDb(merchantDb string) (mongoSession *mgo.Session) {
mongoDBDialInfo := &mgo.DialInfo{
Addrs: []string{DatabaseIpPort},
Username: DbUsername,
Password: DbPassword,
Source: DbSource,
Database: merchantDb,
Timeout: 60 * time.Second,
PoolLimit: 4096,
}
mongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)
if err != nil {
fmt.Printf("CreateSession: %s\n", err)
defer mongoSession.Close()
return mongoSession
}
mongoSession.SetMode(mgo.Monotonic, true)
return mongoSession
}
Example of a model function which connects to db:
func (MerchantDb *MerchantDatabase) UpdateCustomer(uid int, query interface{}) (err error) {
mongoSession := config.ConnectDb(MerchantDb.Database)
defer mongoSession.Close()
sessionCopy := mongoSession.Copy()
defer sessionCopy.Close()
getCollection := sessionCopy.DB(MerchantDb.Database).C("customers")
err = getCollection.Update(bson.M{"uid": uid}, query)
return err
}
How I call this function:
type MerchantDatabase struct {
Database string
}
merchantDb := MerchantDatabase{c.Keys["merchant_db"].(string)}
merchantDb.UpdateUser(7, bson.M{"$set": bson.M{"name": "john"})
Like above code I use different model function for every query & in every model function a new connection is established with mongodb.
My queries are:
- I just passed PoolLimit with the existing code. Is this the way connection pool works? Or there something else?
- Also in my application, there are multiple databases according to merchant. Thats why I call every model function with database signature, so that it can query on that particular database. I am confused about as connection pool works as a cache of connections, can it use one merchant's database connection for other merchant's database ? If yes, how can I prevent this with connection pooling ?
- How can I decide the limit for connection pool for my application ?
I will very grateful to receive the replies.
Thanks!