Go 提供了一個package(golang.org/x/time/rate) 用來方便的對速度進行限制,下面就用示例來說明下如何使用。
首先創(chuàng)建一個rate.Limiter,其有兩個參數(shù),第一個參數(shù)為每秒發(fā)生多少次事件,第二個參數(shù)是其緩存最大可存多少個事件。
rate.Limiter提供了三類方法用來限速
- Wait/WaitN 當沒有可用或足夠的事件時,將阻塞等待 推薦實際程序中使用這個方法
- Allow/AllowN 當沒有可用或足夠的事件時,返回false
- Reserve/ReserveN 當沒有可用或足夠的事件時,返回 Reservation,和要等待多久才能獲得足夠的事件。
Wait/WaitN 示例
package main
import (
"fmt"
"time"
"golang.org/x/net/context"
"golang.org/x/time/rate"
)
func main() {
l := rate.NewLimiter(20, 5)
c, _ := context.WithCancel(context.TODO())
fmt.Println(l.Limit(), l.Burst())
for {
l.Wait(c)
time.Sleep(200 * time.Millisecond)
fmt.Println(time.Now().Format("2016-01-02 15:04:05.000"))
}
}
Allow/AllowN 示例
func main() {
l := rate.NewLimiter(1, 3)
for {
if l.AllowN(time.Now(), 2) {
fmt.Println(time.Now().Format("2016-01-02 15:04:05.000"))
} else {
time.Sleep(6 * time.Second)
}
}
}
Reserve/ReserveN 示例
func main() {
l := rate.NewLimiter(1, 3)
for {
r := l.ReserveN(time.Now(), 3)
time.Sleep(r.Delay())
fmt.Println(time.Now().Format("2016-01-02 15:04:05.000"))
}
}