type RateLimiter interface { // When gets an item and gets to decide how long that item should wait // 根据传入的item返回要等待的时间,传入的item对象会放入到一个map中,该map键为对象item,值为int类型的计数,每调用When,都会增加一次计数 When(item interface{}) time.Duration // Forget indicates that an item is finished being retried. Doesn't matter whether it's for failing // or for success, we'll stop tracking it // 清除map中的键为item的元素 Forget(item interface{}) // NumRequeues returns back how many failures the item has had // 获得map中键为item的数量,即返回map对应键的value NumRequeues(item interface{}) int }
// ItemExponentialFailureRateLimiter does a simple baseDelay*2^<num-failures> limit // dealing with max failures and expiration are up to the caller // 实现了baseDelay*2^x 的指数增长限制 type ItemExponentialFailureRateLimiter struct { failuresLock sync.Mutex // 对象计数map failures map[interface{}]int // 基础延迟 baseDelay time.Duration // 最大延迟 maxDelay time.Duration }
var _ RateLimiter = &ItemExponentialFailureRateLimiter{}
// The backoff is capped such that 'calculated' value never overflows. backoff := float64(r.baseDelay.Nanoseconds()) * math.Pow(2, float64(exp)) if backoff > math.MaxInt64 { return r.maxDelay }
// ItemFastSlowRateLimiter does a quick retry for a certain number of attempts, then a slow retry after that type ItemFastSlowRateLimiter struct { failuresLock sync.Mutex failures map[interface{}]int
maxFastAttempts int fastDelay time.Duration slowDelay time.Duration }
type MaxOfRateLimiter struct { limiters []RateLimiter }
func(r *MaxOfRateLimiter) When(item interface{}) time.Duration { ret := time.Duration(0) for _, limiter := range r.limiters { curr := limiter.When(item) if curr > ret { ret = curr } }