dsiv4041 2019-08-27 21:01
浏览 102
已采纳

如果查询数量过多,goroutines中的GORM将冻结

I've decided to build service what creates CSV report.

In use: Go 1.12, GORM (as 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
  }
}

So when code tries to fetch data it just freezes. If decrease limit and set 100 for example, it runs SQL 2 times and freezes.

Debug() does show nothing as well. As I told seems like it froze. One core from processor loaded.

It works Okay without goroutines. Can you help me to figure out, why it doesn't work in goroutines?

Thanks in advance.

EDIT

maybe my approach is bad and you can suggest, how to fix it. In the end, file should be uploaded to S3 (for example)

  • 写回答

1条回答 默认 最新

  • duanmen1887 2019-08-28 22:28
    关注

    You need to wait for all goroutines to complete before exiting the program.

    func main() {
      ... // init DB connection etc
      wg := sync.WaitGroup{}
      defer db.Close()
      wg.Add(1) // number of goroutines
      go fetch(db, &wg)
      wg.Wait() // wait for goroutines before exiting
    }
    
    func fetch(db *gotm.DB, wg *sync.WaitGroup) {
      .... // 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
        for {} // keeps open process
      }
    }
    

    Otherwise, your program would exit before your goroutines are finished

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据