rate limiting _ golang
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 : .....
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。