在Golang中处理并发的HTTP请求

huangapple go评论115阅读模式
英文:

Process concurrent HTTP requests in Golang

问题

我正在尝试处理一个包含200个URL的文件,并使用每个URL进行HTTP请求。每次最多同时处理10个URL(代码应该在10个URL完成处理之前阻塞)。我尝试用Go解决这个问题,但是我一直得到整个文件都被处理,并创建了200个并发连接。

你应该怎么做呢?

英文:

I'm trying to process a file which contains 200 URLs and use each URL to make an HTTP request. I need to process 10 URLs concurrently maximum each time (code should block until 10 URLs finish processing). Tried to solve it in go but I keep getting the whole file processed with 200 concurrent connection created.

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

What should i do?

答案1

得分: 9

一个包含10个goroutine的池子,从一个通道中读取数据,应该能满足你的需求。

  1. work := make(chan string)
  2. // 获取原始的200个URL
  3. var urlsToProcess []string = seedUrls()
  4. // 启动一个包含10个goroutine的池子,并从work通道中读取URL
  5. for i := 0; i <= 10; i++ {
  6. go func(w chan string) {
  7. url := <-w
  8. }(work)
  9. }
  10. // 将URL写入work通道,阻塞直到一个worker goroutine能够开始工作
  11. for _, url := range urlsToProcess {
  12. work <- url
  13. }

清理和请求结果留给你自己来完成。Go通道会阻塞,直到其中一个worker例程能够读取数据。

英文:

A pool of 10 go routines reading from a channel should fulfill your requirements.

  1. work := make(chan string)
  2. // get original 200 urls
  3. var urlsToProcess []string = seedUrls()
  4. // startup pool of 10 go routines and read urls from work channel
  5. for i := 0; i&lt;=10; i++ {
  6. go func(w chan string) {
  7. url := &lt;-w
  8. }(work)
  9. }
  10. // write urls to the work channel, blocking until a worker goroutine
  11. // is able to start work
  12. for _, url := range urlsToProcess {
  13. work &lt;- url
  14. }

Cleanup and request results are left as an exercise for you. Go channels is will block until one of the worker routines is able to read.

答案2

得分: 2

像这样的代码

  1. longTimeAct := func(index int, w chan struct{}, wg *sync.WaitGroup) {
  2. defer wg.Done()
  3. time.Sleep(1 * time.Second)
  4. println(index)
  5. <-w
  6. }
  7. wg := new(sync.WaitGroup)
  8. ws := make(chan struct{}, 10)
  9. for i := 0; i < 100; i++ {
  10. ws <- struct{}{}
  11. wg.Add(1)
  12. go longTimeAct(i, ws, wg)
  13. }
  14. wg.Wait()
英文:

code like this

  1. longTimeAct := func(index int, w chan struct{}, wg *sync.WaitGroup) {
  2. defer wg.Done()
  3. time.Sleep(1 * time.Second)
  4. println(index)
  5. &lt;-w
  6. }
  7. wg := new(sync.WaitGroup)
  8. ws := make(chan struct{}, 10)
  9. for i := 0; i &lt; 100; i++ {
  10. ws &lt;- struct{}{}
  11. wg.Add(1)
  12. go longTimeAct(i, ws, wg)
  13. }
  14. wg.Wait()

huangapple
  • 本文由 发表于 2016年11月21日 08:26:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/40711091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定