Skip to content

Commit

Permalink
mongo 增加连接池参数
Browse files Browse the repository at this point in the history
  • Loading branch information
nickdu2009 committed Jul 21, 2019
1 parent 909c9ca commit fe2ba6a
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions xmongo/mongo.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package xmongo

import (
"errors"
"fmt"
"github.com/globalsign/mgo"
"github.com/nickxb/pkg/xsync"
"sync"
"time"

"github.com/pkg/errors"

"github.com/globalsign/mgo"
"github.com/nickxb/pkg/xsync"
)

var (
Expand All @@ -15,9 +16,12 @@ var (
)

type MongoConfig struct {
Alias string `json:"alias"`
Url string `json:"url"`
Timeout int `json:"timeout"`
Alias string `json:"alias"`
Url string `json:"url"`
Timeout int `json:"timeout"`
PoolLimit int `json:"pool_limit"`
//单位是秒
PoolTimeout int `json:"pool_timeout"`
}

func InitMongoConfigs(configs []*MongoConfig) error {
Expand All @@ -28,8 +32,10 @@ func InitMongoConfigs(configs []*MongoConfig) error {

s, err := CreateMongoSession(c.Alias, c.Url, time.Duration(c.Timeout)*time.Second)
if err != nil {
return errors.New(fmt.Sprintf("mongo alias %s url %s error %v", c.Alias, c.Url, err))
return errors.Errorf("mongo alias %s url %s error %v", c.Alias, c.Url, err)
}
s.SetPoolLimit(c.PoolLimit)
s.SetPoolTimeout(time.Duration(c.PoolTimeout) * time.Second)
xsync.WithLock(mongoSessionsLock, func() {
mongoSessions[c.Alias] = s
})
Expand Down Expand Up @@ -91,7 +97,7 @@ func DBCollNames(alias string, dbName string) (collNames []string, err error) {
return collNames, nil
}

func DBDatabaseNames(alias string) ([]string, error) {
func DBDatabaseNames(alias string) ([]string, error) {
sess := GetMongoSession(alias)
defer sess.Close()
return sess.DatabaseNames()
Expand All @@ -101,4 +107,4 @@ func WithColl(alias string, dbName string, collName string, fn func(coll *MongoC
coll := NewMongoColl(alias, dbName, collName)
defer coll.Close()
return fn(coll)
}
}

0 comments on commit fe2ba6a

Please sign in to comment.