Connecting to MongoDB Atlas using Golang mgo: Persistent no reachable server to replica set

两盒软妹~` 提交于 2019-12-18 02:43:08

问题


I have a replica set from mongodb atlas, to which I can connect with ANY other language, and regular mongo client, with the url provided with the format :

"mongodb://user:pass@prefix1.mongodb.net:27017,prefix2.mongodb.net:27017,prefix3.mongodb.net:27017/test?&replicaSet=Cluster0-shard-0&authSource=admin"

No matter what I tried, adding ssl=true and removing, nothing works. It is always "no reachable server".

I tried every single combination for url, every combination for dialConfig, and also Dial and DialWithConfig configurations.

What could be the reason ?


回答1:


Using MongoDB Go driver mgo code snippet below to connect to MongoDB Atlas works, using your example data:

import (
    "gopkg.in/mgo.v2"
    "crypto/tls"
    "net"
)

tlsConfig := &tls.Config{}

dialInfo := &mgo.DialInfo{
    Addrs: []string{"prefix1.mongodb.net:27017", 
                    "prefix2.mongodb.net:27017",
                    "prefix3.mongodb.net:27017"},
    Database: "authDatabaseName",
    Username: "user",
    Password: "pass",
}
dialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
    conn, err := tls.Dial("tcp", addr.String(), tlsConfig)
    return conn, err
}
session, err := mgo.DialWithInfo(dialInfo)

Note that you can also specify only one of the replica set members as a seed. For example:

Addrs: []string{"prefix2.mongodb.net:27017"}

See also:

  • tls.Dial()
  • DialInfo
  • DialWithInfo

Update:

You could also use ParseURL() method to parse MongoDB Atlas URI string. However, currently this method does not support SSL (mgo.V2 PR:304)

A work around is to take out the ssl=true line before parsing.

//URI without ssl=true
var mongoURI = "mongodb://username:password@prefix1.mongodb.net,prefix2.mongodb.net,prefix3.mongodb.net/dbName?replicaSet=replName&authSource=admin"

dialInfo, err := mgo.ParseURL(mongoURI)

//Below part is similar to above. 
tlsConfig := &tls.Config{}
dialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
    conn, err := tls.Dial("tcp", addr.String(), tlsConfig)
    return conn, err
}
session, _ := mgo.DialWithInfo(dialInfo)


来源:https://stackoverflow.com/questions/41173720/connecting-to-mongodb-atlas-using-golang-mgo-persistent-no-reachable-server-to

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!