我每天从 API 返回 8000 行,我必须将这些结果保存在我的数据库中。一个接一个地做这件事很疯狂,需要很长时间。因此,我决定尝试一下 goroutines,以发现在 8000 行中只有 1000 行(正负)实际被插入。wg := sync.WaitGroup{}wg.Add(len(xyz.Hours))for _, e := range xyz.Hours { go createDatabaseEntry(e, &wg)}使用 Go 例程,它非常快,但只会插入大约 1000 行,其余的将因任何原因而留空。有人能告诉我将它存储到我的 Postgress 数据库的合适方法是什么吗?我正在使用 GORM 作为数据库库。当我使用下面的代码 (createDatabaseEntry fn) 时,需要 5 分钟以上才能完成。for _, e := range xyz.Hours { msInt, _ := strconv.ParseInt(strconv.Itoa(e.Timestamp), 10, 64) t := time.Unix(0, msInt*int64(time.Millisecond)) ef := models.Xyz{ Timestamp: t, Unit: e.Unit, Value: e.Value, } db.Create(&ef)}让它变慢的不是前两行(strconv),我删除了它们,但将行添加到 Postgres 仍然非常慢。我也尝试进行批量插入,但后来我从 Gorm 得到一长串错误,我不明白为什么。var test []models.XyzFlowfor _, e := range xyz.Hours { msInt, _ := strconv.ParseInt(strconv.Itoa(e.Timestamp), 10, 64) t := time.Unix(0, msInt*int64(time.Millisecond)) test = append(test, models.XyzFlow{ Timestamp: t, Unit: e.Unit, Value: e.Value, })}db.Create(&test)2020/10/29 23:47:39 http: 恐慌服务 [::1]:52886: 反映:在零值 goroutine 35 [运行] 上调用 reflect.Value.Interface:
1 回答

繁华开满天机
TA贡献1816条经验 获得超4个赞
参考 GORM 中的事务会对您有所帮助。
https://gorm.io/docs/transactions.html#A-Specific-Example
如果您在事务中处理并提交多个查询,我认为不会有任何显着的性能负载。
- 1 回答
- 0 关注
- 257 浏览
添加回答
举报
0/150
提交
取消