gpt4 book ai didi

http - 在 Golang 中处理并发 HTTP 请求

转载 作者:数据小太阳 更新时间:2023-10-29 03:38:14 27 4
gpt4 key购买 nike

我正在尝试处理一个包含 200 个 URL 的文件,并使用每个 URL 发出一个 HTTP 请求。我每次最多需要同时处理 10 个 URL(代码应该阻塞,直到 10 个 URL 完成处理)。试图在 go 中解决它,但我一直在处理整个文件,并创建了 200 个并发连接。

for scanner.Scan() { // loop through each url in the file
// send each url to golang HTTPrequest
go HTTPrequest(scanner.Text(), channel, &wg)
}
fmt.Println(<-channel)
wg.Wait()

我该怎么办?

最佳答案

channel 中读取的 10 个 go 例程池应该满足您的要求。

work := make(chan string)

// get original 200 urls
var urlsToProcess []string = seedUrls()

// startup pool of 10 go routines and read urls from work channel
for i := 0; i<=10; i++ {
go func(w chan string) {
url := <-w
}(work)
}

// write urls to the work channel, blocking until a worker goroutine
// is able to start work
for _, url := range urlsToProcess {
work <- url
}

清理和请求结果留给您作为练习。 Go channel 将阻塞,直到其中一个工作例程能够读取。

关于http - 在 Golang 中处理并发 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40711091/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com