From 274402e721f9b04f7a2ed64c6920f456a3b4df91 Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Mon, 13 Nov 2023 11:27:39 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20super=20=E6=96=B0=E5=A2=9E=20Conditiona?= =?UTF-8?q?lRetryByExponentialBackoff=20=E5=87=BD=E6=95=B0=EF=BC=8C?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=8F=AF=E4=B8=AD=E6=96=AD=E7=9A=84=E9=80=80?= =?UTF-8?q?=E9=81=BF=E6=8C=87=E6=95=B0=E7=AE=97=E6=B3=95=E9=87=8D=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/super/retry.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/utils/super/retry.go b/utils/super/retry.go index 9e3f835..85cc9d7 100644 --- a/utils/super/retry.go +++ b/utils/super/retry.go @@ -47,8 +47,20 @@ func RetryByRule(f func() error, rule func(count int) time.Duration) error { // - multiplier:延迟时间的乘数,通常为 2 // - randomization:延迟时间的随机化因子,通常为 0.5 func RetryByExponentialBackoff(f func() error, maxRetries int, baseDelay, maxDelay time.Duration, multiplier, randomization float64) error { + return ConditionalRetryByExponentialBackoff(f, nil, maxRetries, baseDelay, maxDelay, multiplier, randomization) +} + +// ConditionalRetryByExponentialBackoff 该函数与 RetryByExponentialBackoff 类似,但是可以被中断 +// - cond 为中断条件,当 cond 返回 false 时,将会中断重试 +// +// 该函数通常用于在重试过程中,需要中断重试的场景,例如: +// - 用户请求开始游戏,由于网络等情况,进入重试状态。此时用户再次发送开始游戏请求,此时需要中断之前的重试,避免重复进入游戏 +func ConditionalRetryByExponentialBackoff(f func() error, cond func() bool, maxRetries int, baseDelay, maxDelay time.Duration, multiplier, randomization float64) error { retry := 0 for { + if cond != nil && !cond() { + return fmt.Errorf("interrupted") + } err := f() if err == nil { return nil