参考: https://www.cnblogs.com/jackey2015/p/11843626.html
import "golang.org/x/time/rate"
func newLimiter() *rate.Limiter{ limit := rate.Every(10 * time.Microsecond) limiter := rate.NewLimiter(limit, 1) return limiter } func xiaofeiToken(limiter *rate.Limiter) { ok := limiter.Allow() if !ok { fmt.Println("限流ing") }else { fmt.Println("获得令牌",time.Now()) } } func TestLimiter(t *testing.T) { limiter := newLimiter() for i:=0;i<100;i++ { xiaofeiToken(limiter) time.Sleep(50*time.Millisecond) } time.Sleep(2000*time.Millisecond) fmt.Println("第二春") for j:=0;j<100;j++ { fmt.Println(j) go xiaofeiToken(limiter) //time.Sleep(50*time.Millisecond) } }