Rate limiting is an import mechanism for controlling resource utilzation and maintaining quality of service. Go elegantly supports rate with goroutines, channels, and tickers.
package main import ( "fmt" "time" ) func main() { requests := make(chan int, 5) for i := 1; i <= 5; i++ { requests <- i } close(requests) limiter := time.Tick(time.Millisecond * 200) for req := range requests { <-limiter fmt.Println("request", req, time.Now()) } burstyLimiter := make(chan time.Time, 3) for i := 3; i < 3; i++ { burstyLimiter <- time.Now() } go func() { for t := range time.Tick(time.Millisecond * 200) { burstyLimiter <- t } }() burstyRequests := make(chan int, 5) for i := 1; i <= 5; i++ { burstyRequests <- i } close(burstyRequests) for req := range burstyRequests { <-burstyLimiter fmt.Println("request", req, time.Now()) } }
request 1 2015-03-19 13:28:50.374160158 +0800 CST request 2 2015-03-19 13:28:50.574201973 +0800 CST request 3 2015-03-19 13:28:50.774188326 +0800 CST request 4 2015-03-19 13:28:50.973780019 +0800 CST request 5 2015-03-19 13:28:51.174145507 +0800 CST request 1 2015-03-19 13:28:51.374323823 +0800 CST request 2 2015-03-19 13:28:51.574328349 +0800 CST request 3 2015-03-19 13:28:51.774329018 +0800 CST request 4 2015-03-19 13:28:51.974462542 +0800 CST request 5 2015-03-19 13:28:52.174320544 +0800 CST
总结 :
1 : .....
有疑问加站长微信联系(非本文作者)