我正在編寫一個(gè)快速寫入 mongodb 的應(yīng)用程序。mongodb 和 mgo 處理速度太快了。我的問題是,有沒有辦法讓我確定 mongo 跟不上并開始阻塞?但我也不想不必要地阻止。這是模擬問題的代碼示例:package mainimport ( "labix.org/v2/mgo" "time" "fmt")// in database name is a string and age is an inttype 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) }}我經(jīng)常收到以下錯誤:panic: Could not insert into database或者panic: write tcp 127.0.0.1:27017: i/o timeout
2 回答

慕無忌1623718
TA貢獻(xiàn)1744條經(jīng)驗(yàn) 獲得超4個(gè)贊
我懷疑如果你允許 Go 使用多個(gè)線程和Copy() 然后 Close()你的會話,你會獲得更好的性能。
要回答您的問題,這可能是頻道的完美用例。在一個(gè) goroutine 中將項(xiàng)目送入通道,并在另一個(gè) goroutine 中使用它們/將它們寫入 Mongo。您可以調(diào)整通道的大小以滿足您的需要。一旦通道已滿,生產(chǎn)者線程將在嘗試向其發(fā)送時(shí)阻塞。
您可能還想使用Safe()方法設(shè)置。設(shè)置 W:0 將使 Mongo 處于“即發(fā)即忘”模式,這將極大地提高性能,但可能會丟失一些數(shù)據(jù)。您還可以更改超時(shí)時(shí)間。
- 2 回答
- 0 關(guān)注
- 222 瀏覽
添加回答
舉報(bào)
0/150
提交
取消