1. 程式人生 > 實用技巧 >golang mongodb連線池使用姿勢

golang mongodb連線池使用姿勢

配置檔案:

[mongo]
host = 192.168.1.237:27017
username = "ichunt"
password = "huntmon6699"
database = ichunt
maxPoolSize=100

自義定多個mongo資料庫配置

package config


type MongoDbDatabase struct {
    Host        string
    UserName     string
    Password    string
    Database    string
    MaxPoolSize string
}


func BuildMongoDbConfgs () map[
string]MongoDbDatabase{ return map[string]MongoDbDatabase{ "default" : { Host:Get("mongo.host").String(), UserName:Get("mongo.username").String(), Password:Get("mongo.password").String(), Database:Get("mongo.database").String(), MaxPoolSize:Get(
"mongo.maxPoolSize").String(), }, } }

連線池實現:

package mongo

import (
    "fmt"
    "gopkg.in/mgo.v2"
    "search_server/pkg/config"
    "strconv"
)

var session *mgo.Session


type ichuntMongo struct {
    MongoList map[string]*mgo.Session
}

var ichuntMongo_ = &ichuntMongo{}



func getconn(mongoConfig config.MongoDbDatabase) (
*mgo.Session ,error){ url := mongoConfig.Host maxPoolSize := mongoConfig.MaxPoolSize maxPoolSizeInt,err := strconv.Atoi(maxPoolSize) if err != nil{ maxPoolSizeInt = 100 } url += "?maxPoolSize="+maxPoolSize session, err = mgo.Dial(url) if err != nil { return nil ,err } fmt.Println("url",url) fmt.Println("maxPoolSizeInt",maxPoolSizeInt) session.SetPoolLimit(maxPoolSizeInt) session.SetMode(mgo.Monotonic, true) myDB :=session.DB(mongoConfig.Database) err = myDB.Login(mongoConfig.UserName,mongoConfig.Password) if err != nil { return nil ,err } return session,nil } func SetUp() (err error) { err = nil ichuntMongo_.MongoList = make(map[string]*mgo.Session,0) mongodbList := config.BuildMongoDbConfgs() if len(mongodbList) > 0{ for mongoName,mongoConfig := range mongodbList{ ichuntMongo_.MongoList[mongoName],err = getconn(mongoConfig) if err != nil{ break } } } return err } func Conn(connection string) (*mgo.Session){ return ichuntMongo_.MongoList[connection].Copy() }

呼叫方式:

mongodb = mongo.Conn("default");
defer mongodb.Close()