美文网首页
golang 并发实例

golang 并发实例

作者: jojo1313 | 来源:发表于2019-07-09 17:25 被阅读0次

go关键字实现并发请求示例:

package main

import (
    "fmt"
    "runtime"
    "sync"
    "net/http"
    "io/ioutil"
    "time"
)

func echoResult(c chan string){
    wg:=sync.WaitGroup{}
    wg.Add(1)
    go func() {
        select {
        case x,ok := <-c:
            if ok{
                fmt.Println(x)
                wg.Done()
            }else {
                fmt.Println("11111")
                wg.Done()
            }
            return
        }
    }()
    wg.Wait()
}

func httpGet(ip string, ports string, c chan string,wg *sync.WaitGroup) {
    client := &http.Client{  // 设置http client连接超时时间
        Timeout: 5 * time.Second,
    }
    url := fmt.Sprintf("http://%s:%s/status.html", ip, ports)
    fmt.Println(url)
    resp, err := client.Get(url)
    if err != nil {
        c <- fmt.Sprintf("%s:%s error", ip, ports)
        fmt.Println(fmt.Sprintf("%s:%s error", ip, ports))
        wg.Done() //注意wg.Done的放置,确保每次循环都执行
        return
    }
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("can not read body.")
    } else {
        c <- string(body)
        resp.Body.Close()
    }

    wg.Done()
    echoResult(c)
    return

}

func main() {
    runtime.GOMAXPROCS(runtime.NumCPU())
    ports := []string{"8081","8093","8243","8086","8088","83"}
    lenp := len(ports)
    wg := sync.WaitGroup{}   //利用sync.WaitGroup确保goroutine在main程序前执行完成
    wg.Add(lenp)
    c := make(chan string,lenp)

    for i := 0; i <lenp; i++ {
        go httpGet("192.168.0.1",ports[i], c,&wg)

    }
    wg.Wait()

    defer close(c)
    return

}

相关文章

网友评论

      本文标题:golang 并发实例

      本文链接:https://www.haomeiwen.com/subject/uprfkctx.html