golang 异步并发http轮询(爬虫)

目录

一 同步http

二 异步http

三 控制异步并发速度

四 异步并发实现

五 说明


一 同步http

func Http_curl(url string, payload_str string, method string) []byte{
    payload := strings.NewReader(payload_str)
    req, _ := http.NewRequest(method, url, payload)
    req.Header.Add("content-type", "application/x-www-form-urlencoded")
    req.Header.Add("cache-control", "no-cache")
    res, _ := http.DefaultClient.Do(req)
    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)
    //fmt.Println(string(body))
    return body
}

二 异步http

func Http_curl_async(url string, payload_str string, method string){
    go func() {
        Http_curl(url,payload_str,method)
    }()
}

三 控制异步并发速度

var(
    chSem = make(chan int, 5)
)

func Http_curl_async(url string, payload_str string, method string){
    go func() {
        chSem <- 1
        Http_curl(url,payload_str,method)
        <- chSem
    }()
}

四 异步并发实现

package utils

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
    "sync"
)

var(
    chSem = make(chan int, 5)
    chSemWg sync.WaitGroup
)
func Http_curl(url string, payload_str string, method string) []byte{
    payload := strings.NewReader(payload_str)
    req, _ := http.NewRequest(method, url, payload)
    req.Header.Add("content-type", "application/x-www-form-urlencoded")
    req.Header.Add("cache-control", "no-cache")
    res, _ := http.DefaultClient.Do(req)
    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)
    //fmt.Println(string(body))
    return body
}

func Http_curl_async_loop(looptimes int,url string, payload_str string, method string){
    chSemWg.Add(looptimes)
    for i := 0; i < looptimes; i++ {
        cur_i := i
        go func() {
            chSem <- 1
            fmt.Println(cur_i)
            Http_curl(url,payload_str,method)
            <- chSem
            chSemWg.Done()
        }()
    }
    chSemWg.Wait()
}
utils.Http_curl_async_loop(100,"http://www.baidu.com", "s=s01","POST")

五 说明

  • 如果不用wg,轮询没走完程序就会退出
  • 要控制并发速度,不然协程多了,开启和维护的资源也不少

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值