Contents

go第三方库-Cs.opensource.google.go.x.time

Contents

godoc

官网文档

该存储库提供了补充的 Go 时间包

rate

官方限流器

常见用法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main

import (
	"context"
	"fmt"
	"golang.org/x/time/rate"
	"time"
)

func main() {
	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)
	defer cancel()
	if err := limiter.Wait(ctx); err != nil {
		fmt.Println("may not have got a token")
	} else {
		fmt.Println("Got a token", time.Now())
	}
}
1
2
//获取N个令牌
_ = limiter.WaitN(context.Background(), Nexport)
 |