dsaf415212 2016-12-15 21:35
浏览 164

使用Golang mgo连接到MongoDB Atlas:永久性无可达服务器到副本集

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条回答 默认 最新

  • dongqin1075 2017-03-01 03:40
    关注

    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:

    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)
    
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法