用户可借助该项目实现代码的自动重试功能,它提供了简单、无状态的函数式重试机制,支持自定义重试策略和退避算法,能有效处理临时错误,提升程序稳定性。【此简介由AI生成】
| 文件 | 最后提交记录 | 最后更新时间 |
|---|---|---|
| 1 年前 | ||
| 1 年前 | ||
| 1 年前 | ||
| 1 年前 | ||
| 1 年前 | ||
| 1 年前 | ||
| 1 年前 | ||
| 1 年前 | ||
| 1 年前 | ||
| 1 年前 | ||
| 1 年前 | ||
| 1 年前 | ||
| 1 年前 | ||
| 1 年前 |
以下内容由 AI 翻译,如有问题请 点此提交 issue 反馈
重试
一种简单、无状态、函数式的机制,用于重复执行操作直至成功。
项目状态
本项目目前处于“预发布”阶段。尽管代码经过了大量测试,但 API 可能会发生变化。如果您计划使用它,请使用标记版本或将此依赖项纳入您的项目。
话虽如此,此代码已在生产环境中稳定运行多年,并且已被一些相对知名的项目/代码库所采用。
示例
基础
retry.Retry(func(attempt uint) error {
return nil // Do something that may or may not cause an error
})
文件打开
const logFilePath = "/var/log/myapp.log"
var logFile *os.File
err := retry.Retry(func(attempt uint) error {
var err error
logFile, err = os.Open(logFilePath)
return err
})
if err != nil {
log.Fatalf("Unable to open file %q with error %q", logFilePath, err)
}
logFile.Chdir() // Do something with the file
采用策略与退避机制的 HTTP 请求
var response *http.Response
action := func(attempt uint) error {
var err error
response, err = http.Get("https://api.github.com/repos/Rican7/retry")
if err == nil && response != nil && response.StatusCode > 200 {
err = fmt.Errorf("failed to fetch (attempt #%d) with status code: %d", attempt, response.StatusCode)
}
return err
}
err := retry.Retry(
action,
strategy.Limit(5),
strategy.Backoff(backoff.Fibonacci(10*time.Millisecond)),
)
if err != nil {
log.Fatalf("Failed to fetch repository with error %q", err)
}
使用退避抖动进行重试
action := func(attempt uint) error {
return errors.New("something happened")
}
seed := time.Now().UnixNano()
random := rand.New(rand.NewSource(seed))
retry.Retry(
action,
strategy.Limit(5),
strategy.BackoffWithJitter(
backoff.BinaryExponential(10*time.Millisecond),
jitter.Deviation(random, 0.5),
),
)