-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathturbo_bursty_limiter.go
59 lines (46 loc) · 1.18 KB
/
turbo_bursty_limiter.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
package turbo
import (
"golang.org/x/time/rate"
"sync/atomic"
"time"
)
type BurstyLimiter struct {
rateLimiter *rate.Limiter
allowCount int64
preAllowCount int64
}
//tokens : initial tokens
// rates : refill token into buckets at 1/rates persecond
func NewBurstyLimiter(tokens int, rates int) (*BurstyLimiter, error) {
limiter := rate.NewLimiter(rate.Limit(rates), tokens)
return &BurstyLimiter{rateLimiter: limiter}, nil
}
func (self *BurstyLimiter) PermitsPerSecond() int {
return int(self.rateLimiter.Limit())
}
//try acquire token
func (self *BurstyLimiter) AcquireCount(count int) bool {
succ := self.rateLimiter.AllowN(time.Now(), count)
if succ {
atomic.AddInt64(&self.allowCount, int64(count))
}
return succ
}
//acquire token
func (self *BurstyLimiter) Acquire() bool {
succ := self.rateLimiter.Allow()
if succ {
atomic.AddInt64(&self.allowCount, 1)
}
return succ
}
//return 1 : acquired
//return 2 : total
func (self *BurstyLimiter) LimiterInfo() (int, int) {
tmp := atomic.LoadInt64(&self.allowCount)
change := int(tmp - self.preAllowCount)
self.preAllowCount = tmp
return change, int(self.rateLimiter.Limit())
}
func (self *BurstyLimiter) Destroy() {
}