请求超时 (408) 的 http 重试

http retry for Request Timeout (408)

使用 hashicorp go-retryablehttp 库 (https://github.com/hashicorp/go-retryablehttp)

它会自动重试所有 5xx 代码:

retryablehttp performs automatic retries under certain conditions. Mainly, if an error is returned by the client (connection errors, etc.), or if a 500-range response code is received (except 501), then a retry is invoked after a wait period. Otherwise, the response is returned and left to the caller to interpret.

是否可以在 Request Timeout 上重试,例如关于 408 http 状态代码只是 ootb?
或者我应该构建一些自定义包装器?

您可以实施自己的重试策略并将其传递给 Client.CheckRetry 字段。

文档参考:

代码参考:

代码可能类似于

package main

import (
    "context"
    "net/http"

    "github.com/hashicorp/go-retryablehttp"
)

func main() {

    retryClient := retryablehttp.NewClient()
    retryClient.RetryMax = 10
    retryClient.CheckRetry = func(ctx context.Context, resp *http.Response, err error) (bool, error) {
        ok, e := retryablehttp.DefaultRetryPolicy(ctx, resp, err)
        if !ok && resp.StatusCode == http.StatusRequestTimeout {
            return true, nil 
            // return true for a retry, 
            // if e is nil,
            // you might want to populate that error 
            // to propagate it.
            // see https://github.com/hashicorp/go-retryablehttp/blob/02c1586c8f14be23e7eeb522f1094afbabf45e93/client.go#L673
        }
        return ok, e
    }
}

由于源代码在文件 client.go 的第 354 行中指定,您可以配置 CheckRetry 函数以在任何自定义场景中重试。

    // CheckRetry specifies the policy for handling retries, and is called
    // after each request. The default policy is DefaultRetryPolicy.
    CheckRetry CheckRetry

您只需要在下面的类型中编写一个函数并使用该自定义实现配置 retryablehttp.Client.CheckRetry

type CheckRetry func(ctx context.Context, resp *http.Response, err error) (bool, error)