1 Star 0 Fork 0

kade / mcube

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
retry.go 1.67 KB
一键复制 编辑 原始数据 按行查看 历史
kadegolang 提交于 2023-12-13 17:31 . copy
package lock
import (
"sync/atomic"
"time"
)
// RetryStrategy allows to customise the lock retry strategy.
type RetryStrategy interface {
// NextBackoff returns the next backoff duration.
NextBackoff() time.Duration
}
type linearBackoff time.Duration
// LinearBackoff allows retries regularly with customized intervals
func LinearBackoff(backoff time.Duration) RetryStrategy {
return linearBackoff(backoff)
}
// NoRetry acquire the lock only once.
func NoRetry() RetryStrategy {
return linearBackoff(0)
}
func (r linearBackoff) NextBackoff() time.Duration {
return time.Duration(r)
}
type limitedRetry struct {
s RetryStrategy
cnt int64
max int64
}
// LimitRetry limits the number of retries to max attempts.
func LimitRetry(s RetryStrategy, max int) RetryStrategy {
return &limitedRetry{s: s, max: int64(max)}
}
func (r *limitedRetry) NextBackoff() time.Duration {
if atomic.LoadInt64(&r.cnt) >= r.max {
return 0
}
atomic.AddInt64(&r.cnt, 1)
return r.s.NextBackoff()
}
type exponentialBackoff struct {
cnt uint64
min, max time.Duration
}
// ExponentialBackoff strategy is an optimization strategy with a retry time of 2**n milliseconds (n means number of times).
// You can set a minimum and maximum value, the recommended minimum value is not less than 16ms.
func ExponentialBackoff(min, max time.Duration) RetryStrategy {
return &exponentialBackoff{min: min, max: max}
}
func (r *exponentialBackoff) NextBackoff() time.Duration {
cnt := atomic.AddUint64(&r.cnt, 1)
ms := 2 << 25
if cnt < 25 {
ms = 2 << cnt
}
if d := time.Duration(ms) * time.Millisecond; d < r.min {
return r.min
} else if r.max != 0 && d > r.max {
return r.max
} else {
return d
}
}
1
https://gitee.com/go-kade/mcube.git
git@gitee.com:go-kade/mcube.git
go-kade
mcube
mcube
1225d9a674f1

搜索帮助