71 lines
1.6 KiB
Go
71 lines
1.6 KiB
Go
package mongo
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
newMongo "go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
"mongo.games.com/goserver/core/logger"
|
|
|
|
"mongo.games.com/game/common"
|
|
"mongo.games.com/game/mongo"
|
|
)
|
|
|
|
func init() {
|
|
// 读取配置文件
|
|
vp := common.GetViper("mgo", "json")
|
|
// mongo初始化
|
|
conf := &mongo.Config{}
|
|
err := vp.Unmarshal(conf)
|
|
if err != nil {
|
|
panic(fmt.Errorf("mongo config error: %v", err))
|
|
}
|
|
mongo.Init(conf)
|
|
}
|
|
|
|
var globalMongoSession *newMongo.Client
|
|
|
|
func mongoURI(user, password, host string, port int32, options string) string {
|
|
login := ""
|
|
if user != "" {
|
|
login = user + ":" + password + "@"
|
|
}
|
|
if host == "" {
|
|
host = "localhost"
|
|
}
|
|
if port == 0 {
|
|
port = 27017
|
|
}
|
|
if options != "" {
|
|
options = "?" + options
|
|
}
|
|
url := fmt.Sprintf("mongodb://%s%s:%d/admin%s", login, host, port, options)
|
|
return url
|
|
}
|
|
|
|
// NewMongoClient 创建mongo客户端
|
|
// Deprecated: use [mongo.games.com/game/mongo] instead
|
|
func NewMongoClient() (*newMongo.Client, error) {
|
|
if globalMongoSession != nil {
|
|
return globalMongoSession, nil
|
|
}
|
|
cfg, b := MgoSessionMgrSington.GetCfg(G_P, "user")
|
|
if !b {
|
|
return nil, errors.New("not db")
|
|
}
|
|
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
|
|
client, err := newMongo.Connect(ctx, options.Client().ApplyURI(mongoURI(cfg.Username, cfg.Password, cfg.HostName, cfg.HostPort, cfg.Options)))
|
|
if err != nil {
|
|
logger.Logger.Errorf("NewMongoClient error:%v", err)
|
|
return nil, err
|
|
}
|
|
if client == nil {
|
|
return nil, errors.New("not db client")
|
|
}
|
|
globalMongoSession = client
|
|
return client, nil
|
|
}
|