Help us shape the future of Go! Take the 2026 Go Developer Survey

retry

package
v0.5.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package retry 可取消的重试与轮询原语(stdlib-only):带退避的动作重试 + 到 deadline 为止的条件轮询。收编自消费方三类手写形态——SQLite busy 退避 重试(线性递增)、双副本首启的固定间隔回读、并发败者/终态等待的条件轮询。

Index

Constants

This section is empty.

Variables

View Source
var ErrTimeout = errors.New("retry: 轮询超时")

ErrTimeout Poll 超时(调用方按需区分「条件未达成」与真错误)。

Functions

func Do

func Do(ctx context.Context, cfg Config, fn func(attempt int) error) error

Do 执行 fn 至多 Attempts 次,失败按 Config 退避后重试;返回最后一次错误。 退避等待感知 ctx 取消(nil 视为 context.Background())。

func Poll

func Poll(ctx context.Context, interval, timeout time.Duration, cond func() (bool, error)) error

Poll 按 interval 间隔轮询 cond 直到返回 done 或超过 timeout:cond 返回错误 立即中止并透传;超时返回 ErrTimeout(调用方可继续走兜底路径);ctx 取消 透传 ctx.Err()。cond 立即先执行一次(不改语义地覆盖「条件可能已满足」)。

Types

type Config

type Config struct {
	// Attempts 总尝试次数(含首次);<=1 视为 1。
	Attempts int
	// Delay 退避基数。Linear=false 固定间隔;Linear=true 第 i 次失败后等待 Delay*i。
	// Exponential=true 时第 i 次失败后等待 Delay*2^(i-1)(见 Exponential)。
	Delay time.Duration
	// MaxDelay 单次退避上限(<=0 不限)。
	MaxDelay time.Duration
	// Linear true=线性递增退避(Delay*i),false=固定间隔。
	// 与 Exponential 同时为 true 时 Exponential 优先。
	Linear bool
	// Exponential true=指数退避 Delay*2^(attempt-1),受 MaxDelay 封顶。
	// 外部频控(429/5xx)的标准应对姿势。
	Exponential bool
	// Jitter 可选抖动:每次退避在计算结果上叠加 [0, Jitter) 随机量。
	// 0 = 关闭。用于打散同时失败的重试风暴。
	Jitter time.Duration
	// Retryable 判定错误是否可重试;nil = 所有错误都重试。
	Retryable func(error) bool
}

Config 重试参数。零值 = 只执行一次、不重试。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL