一个 go 语言和 MongoDB 的弱智问题

2019-07-02 23:15:37 +08:00
 moodasmood

刚刚开始学 go 语言,在写一个 mongodb 的插入,然后找了官方的 go-mongodb-driver 驱动,但是这玩意官方都不给个文档?只有 GitHub 上面写了十几行 demo 就完事了?这玩意不用连接池吗?到处翻博客,最后写了一个 update 出来,但是请求一高,就崩了

func Update(link string, m bson.M) {
	start := time.Now().UnixNano()
	configInfo := configs.Config()
	//client := GetInstance().client
	//ctx := GetInstance().ctx
	client, _ := mongo.NewClient(options.Client().ApplyURI(configInfo["dburl"].(string)))
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	err := client.Connect(ctx)
	if err != nil {
		fmt.Print("connect error!")
		fmt.Println(err)
	}
	db := client.Database(configInfo["dbDatabase"].(string))
	lianjia := db.Collection(configInfo["dbCollection"].(string))
	_, err = lianjia.UpdateOne(ctx, bson.M{"Link": link}, bson.M{"$set": m})
	if err != nil {
		fmt.Print("update error!")
		fmt.Println(err)
	}

	fmt.Println((time.Now().UnixNano() - start)/ int64(time.Millisecond))
}

报错: update error!context deadline exceeded

这个错误是不是因为我每掉一次函数就新建一个连接?最终连接塞满了造成的?但是网上的文章没看见其他写法呀?官方也没个文档

5590 次点击
所在节点    程序员
10 条回复
tulongtou
2019-07-02 23:59:20 +08:00
翻源码不行么
Maboroshii
2019-07-03 00:29:56 +08:00
仔细找找还是有的。
Additional examples and documentation can be found under the examples directory and on the MongoDB Documentation website.

https://docs.mongodb.com/ecosystem/drivers/go/
https://godoc.org/go.mongodb.org/mongo-driver
iwdmb
2019-07-03 01:14:56 +08:00
```
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
```

將 timeout 調高 eg.

```
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
```

有興趣可以了解一下 context

[https://blog.golang.org/context]( https://blog.golang.org/context)

:)
impl
2019-07-03 01:23:01 +08:00
以前有个 mgo 的库还不错,不过好像没维护了
yuikns
2019-07-03 04:54:06 +08:00
@impl https://github.com/go-mgo/mgo 嘛,后来有个哥们接手了,用的是 https://github.com/globalsign/mgo
修了一些 bug,感觉用起来还不错。

@moodasmood
这个版本的文档主要在 godoc 找 https://godoc.org/github.com/globalsign/mgo 不过因为和 mongo 一致,用起来还行。

然后自己顺手撸了个自动提交...
https://github.com/argcv/stork/blob/master/mongo/ac.go

初始化 client 后,它维护了一个连接池,目前还没出过啥问题。
orqzsf1
2019-07-03 09:46:21 +08:00
检查连通性,可能是你的 link 有问题
skiy
2019-07-03 12:03:35 +08:00
没找到你说的那个。只找到这个: https://github.com/mongodb/mongo-go-driver
zkqiang
2019-07-03 14:24:42 +08:00
@yuikns 这个接手的好像也鸽了?最后 commit 是 2018 年
yuikns
2019-07-03 14:30:31 +08:00
@zkqiang https://github.com/globalsign/mgo/branches

它主要是修了 bug me 和少量更新。master 看来是当 release 用了,development branch 最近更新是两个月前
zkqiang
2019-07-03 14:40:15 +08:00
@yuikns 哦看到了,已 star

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

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

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

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

© 2021 V2EX