【发布时间】:2020-07-07 16:19:14
【问题描述】:
我有一个接收带有此代码的地图切片的频道:
func submitRecords(records []map[string]string) {
batch := []map[string]string{}
ch := make(chan []map[string]string)
batchCt := 1
go func() {
for _, v := range records {
batch = append(batch, v)
if len(batch) == 150 {
ch <- batch
batch = nil
}
}
close(ch)
}()
}
我提交这些记录的 API 接受最多 150 个批次。为了加快速度,我想启动 4 个 go 例程来同时处理通道中的记录。一旦记录进入频道,它们被处理的顺序就无关紧要了。
目前我对上面单独运行的代码进行了以下更新:
func submitRecords(records []map[string]string) {
batch := []map[string]string{}
ch := make(chan []map[string]string)
batchCt := 1
go func() {
for _, v := range records {
batch = append(batch, v)
if len(batch) == 150 {
ch <- batch
batch = nil
}
}
close(ch)
}()
for b := range ch {
str, _ := json.Marshal(b)
fmt.Printf("Sending batch at line %d\n", (batchCt * 150))
payload := strings.NewReader(string(str))
client := &http.Client{}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
}
login, _ := os.LookupEnv("Login")
password, _ := os.LookupEnv("Password")
req.Header.Add("user_name", login)
req.Header.Add("password", password)
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
batchCt++
}
}
我将如何修改它以从通道中提取 4 个 go 例程并发送这些请求?或者,这是否可能/我是否误解了 goroutine 的功能?
【问题讨论】:
-
batch = nil这行不行。 -
为什么?根据我的研究,我发现这是清除切片以重复使用的方法,类似于 python 中的
batch.clear()操作。当我在将记录发送到 API 后检查记录时,看起来一切正常。 -
您的异步循环缺少尾随
ch <- batch,我猜。 -
你的函数是颠倒的。当前正在异步的循环应该是同步的,应该有N个请求处理例程。该函数应该通过等待这 N 个 goroutine 完成来终止。
-
基本上,我将记录添加到
batch切片,直到切片有 150 条记录。一旦达到 150,我将其发送到通道并清除切片。我对 Go 中的并发性比较陌生,所以我可能把一些东西弄混了,它看起来像是在工作
标签: go concurrency