我需要启动多个goroutines来发送http请求。以下是我的代码:
func InteractWithCheck(clusterId int, tableName string, key string, jobs <-chan int, results chan<- objRes) error {
// the host only test
host := "http://xxx.yyy.com/a/b?method=check&"
for _ = range jobs {
url := fmt.Sprintf("%scluster=%d&table=%s&key=%s", host, clusterId, tableName, key)
for intRetry := 0; intRetry < 3; intRetry++ {
resp, err := http.Get(url)
if err != nil {
continue
}
if resp.StatusCode >= 500 {
continue
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
// ...
return nil
}
}
return nil
}
DataCheck
会使用InteractWithCheck
致电go
,代码如下:
func DataCheck(clusterId int, tableName string, keyList []string) error {
// ...
for _, sliceKey := range keyList {
// when len(keyList) > 8000, it will be hang
go InteractWithCheck(clusterId, tableName, sliceKey, jobs, results)
}
for j := 0; j < num; j++ {
jobs <- j
}
close(jobs)
for k := 0; k < num; k++ {
select {
case res := <-results:
// check result
// ...
}
}
return nil
}
当len(keylist) >= 8000
时,程序会挂起,所以我应该优化它吗?
答案 0 :(得分:1)
产生的可用goroutines数量取决于您的RAM,计算机的实时内存。所以,是的,您可以启动8k +,但如果您的计算机无法处理它,则不行。