开发中对于http请求是经常遇到,一般可能网络延迟或接口返回超时,对于发起客户端的请求,除了设置超时时间外,请求重试是很有必要考虑的,我们不用重复造轮子,可以使用https://github.com/rafaeljesus/retry-go第三方库,retry-go的使用非常简单,如下是一个发起 HTTP Get 请求的重试示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
package main
import ( "io/ioutil" "log" "net/http" "time"
"github.com/rafaeljesus/retry-go" )
var ( attempts = 3 //最大重试次数 sleepTime = time.Second * 2 //重试延迟时间 )
func main() { _, err := retry.DoHTTP(func() (*http.Response, error) { return makeRequest() }, attempts, sleepTime) if err != nil { log.Print("retry.DoHTTP Failed") return }
log.Print("retry.DoHTTP OK") }
// 发送http请求 func makeRequest() (*http.Response, error) { client := http.Client{ Timeout: 2 * time.Second, // 设置请求超时时间 } req, err := client.Get("https://www.baidu2.com") // 模拟不存在的url请求 if err != nil { log.Printf(err.Error()) return nil, err }
body, err := ioutil.ReadAll(req.Body) if err != nil { log.Printf(err.Error()) return nil, err } log.Printf("响应数据 %v\\n", string(body)) defer req.Body.Close()
res := &http.Response{} return res, nil } |
运行结果:
我们看到尝试执行了指定的3次请求次数。