我正在使用以下 ssh 隧道命令连接到远程 mongo 服务器:
ssh -i document-db-tun.pem -L 27017:docdb.cluster-cf.us-east-2.docdb.amazonaws.com:27017 ubuntu@ec2-111-111-111-111.us-east-2.compute.amazonaws.com -N
在本地使用 mongo 命令连接到 mongo 服务器也可以正常工作。
但是当我尝试使用 golang 代码在本地连接它时,它会抛出Mongo connection ckeck failed. Err: context deadline exceeded错误。
const (
mongoTimeout = time.Second * 10
)
func initMongo() {
mongoConf := common.Conf.ServiceConfig.Databases.Mongo
ctx, _ := context.WithTimeout(context.Background(), mongoTimeout)
uri := fmt.Sprintf("mongodb://127.0.0.1:27017")
if common.IsSentryEnabled() {
sentry.AddBreadcrumb(&sentry.Breadcrumb{
Message: fmt.Sprintf("Connecting to mongo server at: '%v'", uri),
Category: common.SENTRY_CAT_REPO,
Level: sentry.LevelInfo,
})
}
client := options.Client().
SetReadPreference(readpref.SecondaryPreferred()).
SetAppName("catalog").
SetMaxConnIdleTime(time.Microsecond * 100000).
SetAuth(options.Credential{
Username: mongoConf.Username,
Password: mongoConf.Password,
}).
ApplyURI(uri)
pureMongoClient, err := mongo.Connect(ctx, client)
if err != nil {
if common.IsSentryEnabled() {
sentry.AddBreadcrumb(&sentry.Breadcrumb{
Message: "Error connecting to mongo",
Category: common.SENTRY_CAT_REPO,
Level: sentry.LevelFatal,
})
sentry.ConfigureScope(func(scope *sentry.Scope) {
scope.SetTags(map[string]string{
common.SENTRY_SCOPE_KEY: common.SENTRY_SCOPE_MONGO,
common.SENTRY_TYPE_KEY: common.SENTRY_TYPE_DB,
})
})
sentry.CaptureException(err)
sentry.Flush(time.Second * 5)
}
panic(fmt.Sprintf("Failed to establish mongo connection. Err: %v ", err))
}
}
代码中使用的用户名和密码是连接到远程服务器所需的。使用 golang 代码连接到远程 mongo 服务器时可能会出现什么问题?
慕仙森
慕婉清6462132
Helenr
相关分类