go-pattern-examples/gomore/07_rate_limiting/rate_limiting.go

57 lines
1.1 KiB
Go
Raw Normal View History

2020-04-30 19:16:49 +03:00
package ratelimit
import (
"fmt"
"time"
)
/*
Rate limiting is an very important mechanism
With limiting you can controll resource utilization and maintain quality of service.
Go supports rate limiting by using goroutines, channels, and tickers.
*/
2020-05-08 13:54:32 +03:00
func rateLimiting(requestQueueSize, allowedBurstCount int) {
2020-04-30 19:16:49 +03:00
2020-05-08 13:54:32 +03:00
requests := make(chan int, requestQueueSize)
for i := 1; i <= requestQueueSize; i++ {
2020-04-30 19:16:49 +03:00
requests <- i
}
close(requests)
limiter := time.Tick(200 * time.Millisecond)
for req := range requests {
<-limiter
fmt.Println("request", req, time.Now())
}
2020-05-08 13:54:32 +03:00
//允许的突发数量
burstyLimiter := make(chan time.Time, allowedBurstCount)
2020-04-30 19:16:49 +03:00
2020-05-08 13:54:32 +03:00
//初始化允许突发的数量
for i := 0; i < allowedBurstCount; i++ {
2020-04-30 19:16:49 +03:00
burstyLimiter <- time.Now()
}
2020-05-08 13:54:32 +03:00
//控制请求频率的计时器
2020-04-30 19:16:49 +03:00
go func() {
for t := range time.Tick(200 * time.Millisecond) {
burstyLimiter <- t
}
}()
//请求队列
2020-05-08 13:54:32 +03:00
burstyRequests := make(chan int, requestQueueSize)
for i := 1; i <= requestQueueSize; i++ {
2020-04-30 19:16:49 +03:00
burstyRequests <- i
}
close(burstyRequests)
2020-05-08 13:54:32 +03:00
2020-04-30 19:16:49 +03:00
for req := range burstyRequests {
<-burstyLimiter
fmt.Println("request", req, time.Now())
}
}