-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
78 lines (59 loc) · 1.94 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"github.com/golangdorset/simple-rate-limiting/utils"
"time"
)
func main() {
one()
//two()
//three()
}
// ranging over the channel you can see that we print out the int as soon as it is written in by the feeder.
func one() {
requests := make(chan int, 100)
go utils.Feed(requests)
for i := range requests {
utils.PrintColTwo("out:", i)
}
}
// using a ticker that puts an object on the channel every 1 second, we can delay the reading from the requests queue
// as shown by the rate of requests going in, and being read out
func two() {
requests := make(chan int, 100)
go utils.Feed(requests)
drip := time.Tick(time.Second)
for i := range requests {
<-drip
utils.PrintColTwo("out:", i, utils.PrintNow())
}
}
// feed2 randomly adds up to 20 ints at random intervals, then will sleep for 20 seconds before continuing, this
// allows the "buffer" to re-fill.
// to start with the requests are processed at the same speed they are received, but once the burst of 5 has been used,
// we are back to 1 a second.
func three() {
requests := make(chan int, 100)
go utils.Feed2(requests)
drip := time.Tick(time.Second)
//type of this channel is not important
burstyLimiter := make(chan bool, 5)
// pre-fill the buffer channel so that the first 5 requests can be processes without waiting for the "tick"
for i := 0; i < 5; i++ {
burstyLimiter <- true
}
// in the background, every second (using the drip feed ticker from before) add a "token" to the bursty limiter
// if no requests come in for a period of time, then this "buffer" will fill back to 5
// the next 5 requests will be able to read from the channel and be processed straight away
go func() {
for {
<-drip
burstyLimiter <- true
}
}()
// print the status of the request queue and size of the "buffer" limiter
go utils.PrintChans(requests, burstyLimiter)
for i := range requests {
<-burstyLimiter
utils.PrintColTwo("out:", i, utils.PrintNow())
}
}