猿问

如果查询限制过大,goroutines 中的 GORM 会冻结

我决定建立创建 CSV 报告的服务。


使用中:Go 1.12、GORM(作为 PostgreSQL ORM)


func main() {

  ... // init DB connection etc

  defer db.Close()

  go fetch(db)

  for {} // keeps open process

}


func fetch(db *gotm.DB) {

  .... // some code counts pages, creates file etc

  sqlLimit := 20000 // set limit

  for i := 0; i < pages; i++ {

    db.Table("reports_bookings"),Debug().Where(sql).Offset(i * sqlLimit).Limit(sqlLimit).Find(&myModels)

    .... // code: push it to file

  }

}

因此,当代码尝试获取数据时,它就会冻结。例如,如果减少限制并设置 100,则会运行 SQL 2 次并冻结。


Debug()也没有显示任何内容。正如我所说,它似乎冻结了。已加载处理器的一个核心。


没有 goroutine 也可以正常工作。你能帮我弄清楚为什么它在 goroutine 中不起作用吗?


提前致谢。


编辑


也许我的方法不好,你可以建议如何解决它。最后,文件应该上传到S3(例如)


慕哥6287543
浏览 92回答 1
1回答

HUX布斯

&nbsp; &nbsp; 退出程序之前需要等待所有 goroutine 完成。func main() {&nbsp; ... // init DB connection etc&nbsp; wg := sync.WaitGroup{}&nbsp; defer db.Close()&nbsp; wg.Add(1) // number of goroutines&nbsp; go fetch(db, &wg)&nbsp; wg.Wait() // wait for goroutines before exiting}func fetch(db *gotm.DB, wg *sync.WaitGroup) {&nbsp; .... // some code counts pages, creates file etc&nbsp; sqlLimit := 20000 // set limit&nbsp; for i := 0; i < pages; i++ {&nbsp; &nbsp; db.Table("reports_bookings"),Debug().Where(sql).Offset(i * sqlLimit).Limit(sqlLimit).Find(&myModels)&nbsp; &nbsp; .... // code: push it to file&nbsp; &nbsp; for {} // keeps open process&nbsp; }}否则,你的程序将在 goroutine 完成之前退出
随时随地看视频慕课网APP

相关分类

Go
我要回答