配置文件:

[mongo]
host = 192.168.1.xxx:27017
username = "xxxx"
password = "xxxx"
database = xxxx
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()