package main
import (
"context""fmt""golang.org/x/time/rate""time")
funcmain() {
limiter := rate.NewLimiter(1, 5) // 每秒生成1个令牌,桶的容量是5
for i := 0; i < 10; i++ {
if limiter.Allow() { // Allow是一个阻塞函数,直到获取到令牌返回true,否则一直阻塞
fmt.Println("Got a token", time.Now())
}
}
// 你也可以使用Reserve或者Wait,它们提供了更多的控制选项
reservation := limiter.Reserve()
if !reservation.OK() {
// Not allowed to act! Did you remember to set lim.burst to be > 0 ?
return }
time.Sleep(reservation.Delay())
fmt.Println("Got a token", time.Now())
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defercancel()
if err := limiter.Wait(ctx); err != nil {
fmt.Println("may not have got a token")
} else {
fmt.Println("Got a token", time.Now())
}
}