39 lines
1.1 KiB
Go
39 lines
1.1 KiB
Go
package mongodb
|
|
|
|
import (
|
|
"context"
|
|
"github.com/qiniu/qmgo"
|
|
"go.mongodb.org/mongo-driver/mongo/readpref"
|
|
goproto "google.golang.org/protobuf/proto"
|
|
"service/bizcommon/util"
|
|
"service/library/configcenter"
|
|
"service/library/logger"
|
|
)
|
|
|
|
func NewMongoClient(cfg *configcenter.MongoConfig) (*qmgo.Client, error) {
|
|
clientCfg := &qmgo.Config{
|
|
Uri: cfg.Uri,
|
|
ConnectTimeoutMS: goproto.Int64(cfg.ConnectionTimeoutMs),
|
|
MaxPoolSize: goproto.Uint64(cfg.MaxPoolSize),
|
|
MinPoolSize: goproto.Uint64(0),
|
|
SocketTimeoutMS: goproto.Int64(cfg.SocketTimeoutMs),
|
|
ReadPreference: &qmgo.ReadPref{Mode: readpref.PrimaryMode},
|
|
}
|
|
// 用户名密码
|
|
if len(cfg.Username) > 0 && len(cfg.Password) > 0 {
|
|
clientCfg.Auth = &qmgo.Credential{
|
|
AuthMechanism: "PLAIN",
|
|
AuthSource: "PLAIN",
|
|
Username: cfg.Username,
|
|
Password: cfg.Password,
|
|
PasswordSet: false,
|
|
}
|
|
}
|
|
cli, err := qmgo.NewClient(context.Background(), clientCfg)
|
|
if err != nil {
|
|
logger.Error("NewMongoClient fail, cfg: %v, err: %v", util.ToJson(clientCfg), err)
|
|
return nil, err
|
|
}
|
|
return cli, nil
|
|
}
|