-
Notifications
You must be signed in to change notification settings - Fork 63
/
retry.go
81 lines (69 loc) · 1.71 KB
/
retry.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package util
import (
"time"
)
const (
// defaultRetryAttemptMax Max retry attempts.
defaultRetryAttemptMax = 10
// defaultRetryDurationMin is the initial duration, 100 ms
defaultRetryDurationMin = time.Millisecond * 100
// defaultRetryDurationMax is the max amount of duration, 2000 ms
defaultRetryDurationMax = time.Second * 2
)
//Retry 自带sleep的重试.
type Retry struct {
attempts int
attemptMax int
durationMin time.Duration
durationMax time.Duration
}
// RetryOption retry option.
type RetryOption func(*Retry)
//RetryAttemptMax 设置最大重试次数, 0 为一直重试
func RetryAttemptMax(v int) RetryOption {
return func(r *Retry) { r.attemptMax = v }
}
//RetryDurationMin 最小间隔时间
func RetryDurationMin(v time.Duration) RetryOption {
return func(r *Retry) { r.durationMin = v }
}
//RetryDurationMax 最小间隔时间
func RetryDurationMax(v time.Duration) RetryOption {
return func(r *Retry) { r.durationMax = v }
}
// NewRetry new retry.
func NewRetry(ops ...RetryOption) *Retry {
r := &Retry{
attemptMax: defaultRetryAttemptMax,
durationMin: defaultRetryDurationMin,
durationMax: defaultRetryDurationMax,
}
for _, op := range ops {
op(r)
}
return r
}
//Valid check max attempts
func (r *Retry) Valid() bool {
if r.attemptMax != 0 && r.attempts >= r.attemptMax {
return false
}
return true
}
//Attempts current attempt times.
func (r *Retry) Attempts() int {
return r.attempts
}
// Reset attempts.
func (r *Retry) Reset() {
r.attempts = 0
}
// Next wait sleep.
func (r *Retry) Next() {
dur := time.Duration(time.Now().UnixNano())%(r.durationMin<<uint32(r.attempts)) + r.durationMin
if dur > r.durationMax {
dur = r.durationMax
}
time.Sleep(dur)
r.attempts++
}