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,26 +157,38 @@ 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())
} }
}() }()
mongodbHosts := "" if config.Config.Mongo.Uri != "" {
for i, v := range config.Config.Mongo.Address { uri = config.Config.Mongo.Uri
if i == len(config.Config.Mongo.Address)-1 { } else {
mongodbHosts += v mongodbHosts := ""
for i, v := range config.Config.Mongo.Address {
if i == len(config.Config.Mongo.Address)-1 {
mongodbHosts += v
} else {
mongodbHosts += v + ","
}
}
if config.Config.Mongo.Password != "" && config.Config.Mongo.Username != "" {
uri = fmt.Sprintf("mongodb://%s:%s@%s/%s?maxPoolSize=%d&authSource=admin",
config.Config.Mongo.Username, config.Config.Mongo.Password, mongodbHosts,
config.Config.Mongo.Database, config.Config.Mongo.MaxPoolSize)
} else { } else {
mongodbHosts += v + "," 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( client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
fmt.Sprintf("mongodb://%v:%v@%v/?authSource=admin",
config.Config.Mongo.Username, config.Config.Mongo.Password, mongodbHosts)))
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