go关键字实现并发请求示例:
起Numcpu个进程,并发请求url,输出请求结果。
package main
import (
"fmt"
"runtime"
"sync"
"net/http"
"io/ioutil"
)
func httpGet(ip string, ports []string, c chan string,wg *sync.WaitGroup) {
nums := len(ports)
client := &http.Client{ // 设置http client连接超时时间
Timeout: 5 * time.Second,
}
for i:=0;i<nums;i++{
url := fmt.Sprintf("http://%s:%s/status.html", ip, ports[i])
fmt.Println(url)
resp, err := client.Get(url)
if err != nil {
c <- fmt.Sprintf("%s:%s error", ip, ports[i])
fmt.Println(fmt.Sprintf("%s:%s error", ip, ports[i]))
wg.Done() //注意wg.Done的放置,确保每次循环都执行
continue
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("can not read body.")
} else {
c <- string(body)
resp.Body.Close()
}
wg.Done()
}
}
func main() {
var procs int
runtime.GOMAXPROCS(runtime.NumCPU())
numcpu := runtime.NumCPU()
ports := []string{"80","8080","8020","18133",}
if numcpu>len(ports) {
procs=len(ports)
}else {
procs=numcpu
}
wg := sync.WaitGroup{} //利用sync.WaitGroup确保goroutine在main程序前执行完成
elment := len(ports)/4
wg.Add(len(ports))
c := make(chan string,len(ports))
var start,end int
for i := 0; i <procs; i++ {
if i==procs-1 {
end=len(ports)
}else {
end=start+elment
}
fmt.Println(ports[start:end])
go httpGet("192.168.1.240",ports[start:end], c,&wg)
start +=elment
}
wg.Wait()
fmt.Println("99999999999")
nums := len(c)
fmt.Println(len(c))
for i := 0; i < nums; i++ {
fmt.Println(<-c)
}
defer close(c)
return
}
有疑问加站长微信联系(非本文作者)