Go 实现错误重试

在 Go 中,我们使用https://github.com/cenkalti/backoff来实现错误重试的机制。
import中导入github.com/cenkalti/backoff/v4

代码

代码如下:

package main

import (
    "fmt"
    "io"
    "io/ioutil"
    "log"
    "net/http"
    "time"

    "github.com/cenkalti/backoff/v4"
)

func main() {
    client := http.Client{
        Timeout: 5 * time.Second,
    }
    operation := func() error {
        resp, err := client.Get("https://www.google.com")
        if err != nil {
            return err
        }
        defer func() {
            _ = resp.Body.Close()
        }()
        if resp.StatusCode/100 != 2 {
            body, err := ioutil.ReadAll(resp.Body)
            if err != nil {
                return err
            }
            return fmt.Errorf("response data:%s", body)
        }
        io.Copy(ioutil.Discard, resp.Body)
        return nil
    }
    err := backoff.RetryNotify(
        operation,
        backoff.WithMaxRetries(backoff.NewExponentialBackOff(), 3),
        func(err error, duration time.Duration) {
            log.Printf("failed err:%s,and it will be executed again in %v", err.Error(), duration)
        })
    if err != nil {
        log.Fatal(err)
    }
}

结果

执行结果如下:


image.png

分析

至少会执行1次,最多会重试3次。

你可能感兴趣的:(Go 实现错误重试)