我正在编写一个快速写入 mongodb 的应用程序。 mongodb 和 mgo 处理得太快了。我的问题是,有没有办法让我确定 mongo 跟不上并开始阻塞?但我也不想无谓地阻止。 以下是模拟问题的代码示例:
package main
import (
"labix.org/v2/mgo"
"time"
"fmt"
)
// in database name is a string and age is an int
type Dog struct{
Breed string "breed"
}
type Person struct{
Name string "name"
Pet Dog `bson:",inline"`
Ts time.Time
}
func insert(session *mgo.Session, bob Person){
err := session.DB("db_log").C("people").Insert(&bob)
if err != nil {
panic("Could not insert into database")
}
}
func main() {
session, _ := mgo.Dial("localhost:27017")
bob := Person{Name : "Robert", Pet : Dog{}}
i := 0
for {
time.Sleep(time.Duration(1) * time.Microsecond)
i++
go insert(session, bob)
}
}
我经常遇到这样的错误:
panic: Could not insert into database
或
panic: write tcp 127.0.0.1:27017: i/o timeout
最佳答案
我怀疑如果你 allow Go to use multiple threads 你会得到更好的表现和 Copy() then Close()你的 session 。
为了回答您的问题,这可能是 channel 的完美用例。在一个 goroutine 中将项目输入 channel 并在另一个 goroutine 中使用它们/将它们写入 Mongo。您可以调整 channel 的大小以满足您的需要。一旦 channel 已满,生产者线程将在尝试向其发送时阻塞。
您可能还想玩一下 Safe()方法设置。设置 W:0 将使 Mongo 进入“即发即弃”模式,这将显着加快性能,但可能会丢失一些数据。您还可以更改超时时间。
关于Golang Mgo 节奏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21346079/