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-21 07:28:53 +03:00
|
|
|
|
func rateLimiting(requestQueue chan int, duration int64, allowedBurstCount int) {
|
2020-04-30 19:16:49 +03:00
|
|
|
|
|
2020-05-21 07:28:53 +03:00
|
|
|
|
//根据允许的突发数量,创建ch
|
|
|
|
|
//只要该队列中有内容,就可以一直取出来,即便ch已经关闭
|
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() {
|
2020-05-21 07:28:53 +03:00
|
|
|
|
for t := range time.Tick(time.Duration(duration) * time.Millisecond) {
|
2020-04-30 19:16:49 +03:00
|
|
|
|
burstyLimiter <- t
|
|
|
|
|
}
|
|
|
|
|
}()
|
|
|
|
|
|
2020-05-21 07:28:53 +03:00
|
|
|
|
for req := range requestQueue {
|
|
|
|
|
<-burstyLimiter //突发控制器是限流的关键
|
|
|
|
|
fmt.Println("request", req, time.Now())
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func simpleRateLimiting(duration int64, requestQueueSize int) {
|
|
|
|
|
|
|
|
|
|
requests := make(chan int, requestQueueSize)
|
2020-05-08 13:54:32 +03:00
|
|
|
|
for i := 1; i <= requestQueueSize; i++ {
|
2020-05-21 07:28:53 +03:00
|
|
|
|
requests <- i
|
2020-04-30 19:16:49 +03:00
|
|
|
|
}
|
2020-05-21 07:28:53 +03:00
|
|
|
|
close(requests)
|
|
|
|
|
|
|
|
|
|
limiter := time.Tick(time.Duration(duration) * time.Millisecond)
|
2020-05-08 13:54:32 +03:00
|
|
|
|
|
2020-05-21 07:28:53 +03:00
|
|
|
|
for req := range requests {
|
|
|
|
|
<-limiter
|
2020-04-30 19:16:49 +03:00
|
|
|
|
fmt.Println("request", req, time.Now())
|
|
|
|
|
}
|
|
|
|
|
}
|