Add rate limiting
This commit is contained in:
parent
fd31a65843
commit
b72ebaf843
6
main.go
6
main.go
@ -13,7 +13,8 @@ package main
|
|||||||
// import "git.sangeeth.dev/gobyexample/timers"
|
// import "git.sangeeth.dev/gobyexample/timers"
|
||||||
// import "git.sangeeth.dev/gobyexample/tickers"
|
// import "git.sangeeth.dev/gobyexample/tickers"
|
||||||
// import "git.sangeeth.dev/gobyexample/workerpools"
|
// import "git.sangeeth.dev/gobyexample/workerpools"
|
||||||
import "git.sangeeth.dev/gobyexample/waitgroups"
|
// import "git.sangeeth.dev/gobyexample/waitgroups"
|
||||||
|
import "git.sangeeth.dev/gobyexample/ratelimiting"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// runes.Runes()
|
// runes.Runes()
|
||||||
@ -29,5 +30,6 @@ func main() {
|
|||||||
// timers.Timers()
|
// timers.Timers()
|
||||||
// tickers.Tickers()
|
// tickers.Tickers()
|
||||||
// workerpools.WorkerPools()
|
// workerpools.WorkerPools()
|
||||||
waitgroups.WaitGroups()
|
// waitgroups.WaitGroups()
|
||||||
|
ratelimiting.RateLimiting()
|
||||||
}
|
}
|
||||||
|
55
ratelimiting/ratelimiting.go
Normal file
55
ratelimiting/ratelimiting.go
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
package ratelimiting
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func basicRateLimiting() {
|
||||||
|
reqs := make(chan int, 5)
|
||||||
|
limiter := time.Tick(200 * time.Millisecond)
|
||||||
|
|
||||||
|
for i := range 5 {
|
||||||
|
reqs <- i
|
||||||
|
}
|
||||||
|
close(reqs)
|
||||||
|
|
||||||
|
for i := range reqs {
|
||||||
|
<-limiter
|
||||||
|
fmt.Printf("request %d at %v\n", i, time.Now())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func burstyRateLimiting() {
|
||||||
|
burstyLimiter := make(chan time.Time, 3)
|
||||||
|
|
||||||
|
// Fill burstyLimiter to brim first
|
||||||
|
for range 3 {
|
||||||
|
burstyLimiter <- time.Now()
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
for t := range time.Tick(200 * time.Millisecond) {
|
||||||
|
burstyLimiter <- t
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
reqs := make(chan int, 5)
|
||||||
|
|
||||||
|
for i := range 5 {
|
||||||
|
reqs <- i
|
||||||
|
}
|
||||||
|
close(reqs)
|
||||||
|
|
||||||
|
for i := range reqs {
|
||||||
|
t := <-burstyLimiter
|
||||||
|
fmt.Printf("request %d at %v\n", i, t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func RateLimiting() {
|
||||||
|
fmt.Println("Demo-ing basic rate limiting")
|
||||||
|
basicRateLimiting()
|
||||||
|
fmt.Println("Demo-ing bursty rate limiting")
|
||||||
|
burstyRateLimiting()
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user