golang流量控制

package main

import "time"
import (
	"github.com/golang/glog"
)

func main() {

	//requests := make(chan int, 5)
	//for i := 1; i <= 5; i++ {
	//	requests <- i
	//}
	//close(requests)
	//
	//limiter := time.Tick(200 * time.Millisecond)
	//
	//for req := range requests {
	//	<-limiter
	//	glog.Info("request", req, time.Now())
	//}

	burstyLimiter := make(chan time.Time, 3)

	for i := 0; i < 3; i++ {
		burstyLimiter <- time.Now()
	}

	go func() {
		//for t := range time.Tick(200 * time.Millisecond) {
		for range time.Tick(200 * time.Millisecond) {
			for i := 0; i < 3; i++ {
				burstyLimiter <- time.Now()
			}
			//burstyLimiter <- t
		}
	}()

	burstyRequests := make(chan int, 30)
	for i := 1; i <= 30; i++ {
		burstyRequests <- i
	}
	close(burstyRequests)
	for req := range burstyRequests {
		<-burstyLimiter
		glog.Info("request", req, time.Now())
	}
}

结果如下
request1 2020-07-13 16:40:05.900113 +0800 CST m=+0.002950864
request2 2020-07-13 16:40:05.9003 +0800 CST m=+0.003137902
request3 2020-07-13 16:40:05.900321 +0800 CST m=+0.003158913
request4 2020-07-13 16:40:06.104337 +0800 CST m=+0.207172945
request5 2020-07-13 16:40:06.104502 +0800 CST m=+0.207338138
request6 2020-07-13 16:40:06.104537 +0800 CST m=+0.207372952
request7 2020-07-13 16:40:06.303792 +0800 CST m=+0.406626954
request8 2020-07-13 16:40:06.303896 +0800 CST m=+0.406731173
request9 2020-07-13 16:40:06.303995 +0800 CST m=+0.406829851
request10 2020-07-13 16:40:06.503244 +0800 CST m=+0.606077214
request11 2020-07-13 16:40:06.503323 +0800 CST m=+0.606156100
request12 2020-07-13 16:40:06.503345 +0800 CST m=+0.606178516
request13 2020-07-13 16:40:06.704053 +0800 CST m=+0.806884799
request14 2020-07-13 16:40:06.704221 +0800 CST m=+0.807053386
request15 2020-07-13 16:40:06.70433 +0800 CST m=+0.807161676
request16 2020-07-13 16:40:06.904782 +0800 CST m=+1.007612931
request17 2020-07-13 16:40:06.90501 +0800 CST m=+1.007840196
request18 2020-07-13 16:40:06.905038 +0800 CST m=+1.007868590
request19 2020-07-13 16:40:07.101089 +0800 CST m=+1.203918385
request20 2020-07-13 16:40:07.101135 +0800 CST m=+1.203964080
request21 2020-07-13 16:40:07.101141 +0800 CST m=+1.203969567
request22 2020-07-13 16:40:07.305304 +0800 CST m=+1.408131097
request23 2020-07-13 16:40:07.305351 +0800 CST m=+1.408178845
request24 2020-07-13 16:40:07.305363 +0800 CST m=+1.408190715
request25 2020-07-13 16:40:07.504234 +0800 CST m=+1.607060048
request26 2020-07-13 16:40:07.50428 +0800 CST m=+1.607105608
request27 2020-07-13 16:40:07.504292 +0800 CST m=+1.607117657
request28 2020-07-13 16:40:07.705046 +0800 CST m=+1.807870760
request29 2020-07-13 16:40:07.705153 +0800 CST m=+1.807978366
request30 2020-07-13 16:40:07.705185 +0800 CST m=+1.808010207

你可能感兴趣的:(go语言)