遇到了一个关于连接 Mongodb 的怪事,帮判断一下

2020-05-21 15:25:31 +08:00
 Vegetable

可能触及到我知识的盲区了

情景

本地使用 ssh -L 127.0.0.1:27017:{aliyun.mongodburi}:3717 {user}@{ip} 建立 ssh 通道,将本地的 27017 端口映射到服务器,访问阿里云的 mongodb (无验证),然后在本地运行一些脚本。

映射应该没问题

$ curl 127.0.0.1:27017
It looks like you are trying to access MongoDB over HTTP on the native driver port.

在用 pymongo 时一切正常。

client = MongoClient() # pretty well

今天用了 https://github.com/mongodb/mongo-go-driver,发现在本地无法连接,一直超时。

func initMongoConnection() {
	ctx, _ := context.WithTimeout(context.Background(), time.Second*10)
	log.Println(config.Mongo.URI) // "mongodb://localhost:27017"
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(config.Mongo.URI))
	if err != nil {
		panic(err)
	}
	err = client.Ping(ctx, readpref.Primary())
	if err != nil {
		panic(err) //panic: context deadline exceeded
	}
}

编译之后拿到服务器上去跑又没问题(基本可以定位问题出现在通道上)。本地不走通道访问另一台局域网的 MongoDB,也没问题。
本地到 ssh 服务器的连接速度问题应该可以排除 总结就是:

有可能是哪里的问题?

1664 次点击
所在节点    Go 编程语言
3 条回复
defunct9
2020-05-21 15:29:56 +08:00
没道理
Vegetable
2020-05-21 16:02:14 +08:00
@defunct9 uri 加一句?connect=direct 就能正确连接了,浪费了生命中的一个小时
dafsic
2020-05-21 16:19:42 +08:00
config.Mongo.URI 这个是一个集群的地址,但端口映射只映射了集群中一个主机的地址,是不是这个原因?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/674031

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX