update connect opts - add read pref mode
This commit is contained in:
parent
06e5ae471c
commit
6e0cbfd141
15
mongodb.go
15
mongodb.go
|
@ -25,6 +25,7 @@ type ConnectTLSOpts struct {
|
||||||
CaFile string
|
CaFile string
|
||||||
CertKeyFile string
|
CertKeyFile string
|
||||||
CertKeyFilePassword string
|
CertKeyFilePassword string
|
||||||
|
ReadPreferenceMode string
|
||||||
}
|
}
|
||||||
|
|
||||||
// ConnectStandaloneOpts ...
|
// ConnectStandaloneOpts ...
|
||||||
|
@ -83,7 +84,7 @@ func connectWithTLS(cfg Config) (*mongo.Database, error) {
|
||||||
pwd := base64DecodeToString(opts.CertKeyFilePassword)
|
pwd := base64DecodeToString(opts.CertKeyFilePassword)
|
||||||
s := "%s/?tls=true&tlsCAFile=./%s&tlsCertificateKeyFile=./%s&tlsCertificateKeyFilePassword=%s&authMechanism=MONGODB-X509"
|
s := "%s/?tls=true&tlsCAFile=./%s&tlsCertificateKeyFile=./%s&tlsCertificateKeyFilePassword=%s&authMechanism=MONGODB-X509"
|
||||||
uri := fmt.Sprintf(s, cfg.Host, caFile.Name(), certFile.Name(), pwd)
|
uri := fmt.Sprintf(s, cfg.Host, caFile.Name(), certFile.Name(), pwd)
|
||||||
readPref := readpref.SecondaryPreferred()
|
readPref := getReadPref(opts.ReadPreferenceMode)
|
||||||
clientOpts := options.Client().SetReadPreference(readPref).SetReplicaSet(opts.ReplSet).ApplyURI(uri)
|
clientOpts := options.Client().SetReadPreference(readPref).SetReplicaSet(opts.ReplSet).ApplyURI(uri)
|
||||||
client, err := mongo.Connect(ctx, clientOpts)
|
client, err := mongo.Connect(ctx, clientOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -102,3 +103,15 @@ func connectWithTLS(cfg Config) (*mongo.Database, error) {
|
||||||
func GetInstance() *mongo.Database {
|
func GetInstance() *mongo.Database {
|
||||||
return db
|
return db
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getReadPref(mode string) *readpref.ReadPref {
|
||||||
|
m, err := readpref.ModeFromString(mode)
|
||||||
|
if err != nil {
|
||||||
|
m = readpref.SecondaryPreferredMode
|
||||||
|
}
|
||||||
|
readPref, err := readpref.New(m)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("mongodb.getReadPref err: ", err, m)
|
||||||
|
}
|
||||||
|
return readPref
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue