service/library/mongodb/client.go

39 lines
1.1 KiB
Go
Raw Normal View History

2023-12-21 22:17:40 +08:00
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
}