CreateSession:没有可访问的服务器-mgo [英] CreateSession: no reachable servers - mgo

查看:66
本文介绍了CreateSession:没有可访问的服务器-mgo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用mgo连接到MongoDB Atlas免费集群.

I'm trying to connect to MongoDB Atlas free cluster using mgo.

Golang代码-

package main

import (
     "fmt"
     "gopkg.in/mgo.v2"
     "time"
     "log"
)

const (
    AuthDatabase = "mydatabase"
    AuthUserName = "databaseadmin"
    AuthPassword = "databasepassword"
    ReplicaSetName = "myproject-shard-0"
)

func main(){

MongoDBHosts := []string{
    "myproject-shard-00-00-w4vds.mongodb.net:27017",
    "myproject-shard-00-01-w4vds.mongodb.net:27017",
    "myproject-shard-00-02-w4vds.mongodb.net:27017",
}

mongoDBDialInfo := &mgo.DialInfo{
    Addrs:    MongoDBHosts,
    Timeout:  60 * time.Second,
    Database: AuthDatabase,
    Username: AuthUserName,
    Password: AuthPassword,
    ReplicaSetName: ReplicaSetName,
}

mongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)
if err != nil {
    log.Fatalf("CreateSession: %s\n", err)
}

defer  mongoSession.Close()
fmt.Printf("Connected to replica set %v!\n", mongoSession.LiveServers())
}

错误消息-

CreateSession:没有可访问的服务器

CreateSession: no reachable servers

环境

我正在将mongodb免费集群与Google App Engine GO SDK一起使用

I'm using mongodb free cluster with Google App Engine GO SDK

推荐答案

要连接到MongoDB Atlas,您需要SSL

To connect to MongoDB Atlas, you need SSL

先决条件

TLS/SSL

    Clients must have support for TLS/SSL to connect to an Atlas cluster.

    Clients must have support for the SNI TLS extension to connect to an Atlas M0 Free Tier cluster.


Whitelist

    To access a cluster, you must connect from an IP address on the Atlas group’s IP whitelist. If you need to add an IP address to the whitelist, you can do so in the Connect dialog. You can also add the IP address from the Security tab.

因此我不得不更改以下代码

Thus I had to change the following piece of code

mongoDBDialInfo := &mgo.DialInfo{
    Addrs:    MongoDBHosts,
    Timeout:  60 * time.Second,
    Database: AuthDatabase,
    Username: AuthUserName,
    Password: AuthPassword,
    ReplicaSetName: ReplicaSetName,
}

mongoDBDialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
        conn, err := tls.Dial("tcp", addr.String(), tlsConfig)
        return conn, err
    }

我也必须导入以下内容

"crypto/tls" 
"net"

这篇关于CreateSession:没有可访问的服务器-mgo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆