// 通过处理每个请求时管道接收值的阻塞,我们限制每200毫秒只处理一个请求 for req := range requests { <-limiter fmt.Println("request", req, time.Now()) }
// 某些时候可能希望在保持整体限速规则下允许少量的请求不受限制 // 可以通过含有缓冲区的管道来实现 // burstyLimiter管道可以使同时处理的请求达到3个 burstyLimiter := make(chan time.Time, 3) for i := 0; i < 3; i++ { burstyLimiter <- time.Now() }
// 每200毫秒发送给burstyLimiter管道一个值 gofunc() { for t := range time.Tick(time.Millisecond * 200) { burstyLimiter <- t } }()
// 模拟5个新的请求,前三个请求由于burstyLimiter管道缓冲区的处理可以突破200毫秒的限制 burstyRequests := make(chanint, 5) for i := 1; i <= 5; i++ { burstyRequests <- i } close(burstyRequests)
for req := range burstyRequests { <-burstyLimiter fmt.Println("request", req, time.Now()) } }
tashuo:golang ta_shuo$ go run ticker.go Tick at 2017-09-06 11:47:35.512980179 +0800 CST Tick at 2017-09-06 11:47:36.012186259 +0800 CST Tick at 2017-09-06 11:47:36.515210336 +0800 CST Ticker stoped