-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
59 lines (49 loc) · 1.14 KB
/
main.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 ratelimiting
import (
"fmt"
"time"
)
/*
Rate limiting is an important mechanism for controlling resource
utilisation and maintaining quality of service. Go elegantly
supports rate limiting with goroutines, channels and tickers.
*/
func Run() {
basicRateLimiting()
burstyRateLimiting()
}
// Limit the channel reads to every 200 milliseconds.
func basicRateLimiting() {
requests := make(chan int, 5)
for i := 1; i <= 5; i++ {
requests <- i
}
close(requests)
limiter := time.NewTicker(1000 * time.Millisecond)
for request := range requests {
<-limiter.C
fmt.Println("Throttled request", request, time.Now())
}
}
// Allow short burts of request rates. Buffering the channel
// Allows upto 3 bursts of events.
func burstyRateLimiting() {
burstyLimiter := make(chan time.Time, 3)
for i := 0; i < 3; i++ {
burstyLimiter <- time.Now()
}
go func() {
for t := range time.NewTicker(1000 * time.Millisecond).C {
burstyLimiter <- t
}
}()
requests := make(chan int, 5)
for i := 1; i <= 5; i++ {
requests <- i
}
close(requests)
for request := range requests {
<-burstyLimiter
fmt.Println("request", request, time.Now())
}
}