fix: mogodb url connent (#1232)

* fix: mogodb url connent

* fix: mogodb url connent

* fix: mogodb url connent

* mogodb url connent

* mogodb url connent
pull/1256/head
dong 1 year ago committed by GitHub
parent b3d2f3b182
commit 4b231716c3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -35,7 +35,6 @@ import (
"github.com/go-zookeeper/zk" "github.com/go-zookeeper/zk"
"go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"gorm.io/driver/mysql" "gorm.io/driver/mysql"
"gorm.io/gorm" "gorm.io/gorm"
@ -158,11 +157,15 @@ func checkMysql() error {
func checkMongo() error { func checkMongo() error {
var client *mongo.Client var client *mongo.Client
uri := "mongodb://sample.host:27017/?maxPoolSize=20&w=majority"
defer func() { defer func() {
if client != nil { if client != nil {
client.Disconnect(context.TODO()) client.Disconnect(context.TODO())
} }
}() }()
if config.Config.Mongo.Uri != "" {
uri = config.Config.Mongo.Uri
} else {
mongodbHosts := "" mongodbHosts := ""
for i, v := range config.Config.Mongo.Address { for i, v := range config.Config.Mongo.Address {
if i == len(config.Config.Mongo.Address)-1 { if i == len(config.Config.Mongo.Address)-1 {
@ -171,13 +174,21 @@ func checkMongo() error {
mongodbHosts += v + "," mongodbHosts += v + ","
} }
} }
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI( if config.Config.Mongo.Password != "" && config.Config.Mongo.Username != "" {
fmt.Sprintf("mongodb://%v:%v@%v/?authSource=admin", uri = fmt.Sprintf("mongodb://%s:%s@%s/%s?maxPoolSize=%d&authSource=admin",
config.Config.Mongo.Username, config.Config.Mongo.Password, mongodbHosts))) config.Config.Mongo.Username, config.Config.Mongo.Password, mongodbHosts,
config.Config.Mongo.Database, config.Config.Mongo.MaxPoolSize)
} else {
uri = fmt.Sprintf("mongodb://%s/%s/?maxPoolSize=%d&authSource=admin",
mongodbHosts, config.Config.Mongo.Database,
config.Config.Mongo.MaxPoolSize)
}
}
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err != nil { if err != nil {
return errs.Wrap(err) return errs.Wrap(err)
} else { } else {
err = client.Ping(context.TODO(), &readpref.ReadPref{}) err = client.Ping(context.TODO(), nil)
if err != nil { if err != nil {
return errs.Wrap(err) return errs.Wrap(err)
} }

Loading…
Cancel
Save