我正在查找有关如何有效执行大量 HTTP 请求的知识,我遇到了这个答案: https: //stackoverflow.com/a/23319730/749851,代码如下:package mainimport ( "flag" "fmt" "log" "net/http" "runtime" "time")var ( reqs int max int)func init() { flag.IntVar(&reqs, "reqs", 1000000, "Total requests") flag.IntVar(&max, "concurrent", 200, "Maximum concurrent requests")}type Response struct { *http.Response err error}// Dispatcherfunc dispatcher(reqChan chan *http.Request) { defer close(reqChan) for i := 0; i < reqs; i++ { req, err := http.NewRequest("GET", "http://localhost/", nil) if err != nil { log.Println(err) } reqChan <- req }}// Worker Poolfunc workerPool(reqChan chan *http.Request, respChan chan Response) { t := &http.Transport{} for i := 0; i < max; i++ { go worker(t, reqChan, respChan) }}// Workerfunc worker(t *http.Transport, reqChan chan *http.Request, respChan chan Response) { for req := range reqChan { resp, err := t.RoundTrip(req) r := Response{resp, err} respChan <- r }}// Consumerfunc consumer(respChan chan Response) (int64, int64) { var ( conns int64 size int64 ) for conns < int64(reqs) { select { case r, ok := <-respChan: if ok { if r.err != nil { log.Println(r.err) } else { size += r.ContentLength if err := r.Body.Close(); err != nil { log.Println(r.err) } } conns++ } } } return conns, size}我来自节点,所以我不太理解这个“go”代码。它的哪一部分将它限制为一次 500 个 HTTP 操作?它是以 500 块为单位运行,等到 500 块完成然后开始新的 500,还是它总是在达到 499 时再添加 1,等等。我看到“workerPool”func 循环次数仅与最大并发请求数一样多,调用“worker”500 次,但接下来的 500 次甚至整个 100 万次它是如何完成的?
目前暂无任何回答
- 0 回答
- 0 关注
- 69 浏览
添加回答
举报
0/150
提交
取消