zoukankan      html  css  js  c++  java
  • golang mongodb连接池使用姿势

    配置文件:

    [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()
  • 相关阅读:
    北京师范大学2016考研复试分数线
    中国人民大学2016考研复试基本分数线
    厦门大学2016年硕士研究生复试基本分数线
    上海交通大学2016年硕士复试基本分数线
    swift
    swift
    swift
    iOS 开发自定义一个提示框
    swift
    swift
  • 原文地址:https://www.cnblogs.com/sunlong88/p/13389669.html
Copyright © 2011-2022 走看看