使用Go http重试请求

原文连接:https://www.zhoubotong.site/post/78.html
开发中对于http请求是经常遇到,一般可能网络延迟或接口返回超时,对于发起客户端的请求,

除了设置超时时间外,请求重试是很有必要考虑的,我们不用重复造轮子,可以使用 https://github.com/rafaeljesus/retry-go 第三方库,

retry-go的使用非常简单,如下是一个发起 HTTP Get 请求的重试示例 :

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
}

运行结果:
image.png
我们看到尝试执行了指定的3次请求次数。

posted @   周伯通之草堂  阅读(932)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· Open-Sora 2.0 重磅开源!
点击右上角即可分享
微信分享提示