发布时间:2024-12-22 17:30:22
示例代码:
```go package main import ( "fmt" "time" "golang.org/x/time/rate" ) func main() { l := rate.NewLimiter(10, 1) // 每秒放入10个令牌,允许的最大并发数为10 for i := 0; i < 20; i++ { if l.Allow() { // 判断是否允许通过 fmt.Println("Request", i, "allowed at", time.Now()) } else { fmt.Println("Request", i, "rejected at", time.Now()) } time.Sleep(time.Second) } } ``` 上述示例中,我们创建了一个限制每秒放入10个令牌的`Limiter`,并模拟了20个请求的到来。在每个请求到来时,通过`l.Allow()`方法来判断是否允许通过。运行结果如下: ``` Request 0 allowed at 2019-12-01 14:15:00.000 Request 1 allowed at 2019-12-01 14:15:01.000 ... Request 10 rejected at 2019-12-01 14:15:10.000 Request 11 allowed at 2019-12-01 14:15:11.000 ... ``` 从结果中可以看出,前10个请求都被允许通过,而第11个请求因为令牌桶已满被拒绝。示例代码:
```go package main import ( "fmt" "time" "github.com/oooldking/log/leakybucket" ) func main() { bucket := leakybucket.NewLeakyBucket(10, 2) // 容量为10,每秒放入2个令牌的漏斗 for i := 0; i < 20; i++ { if bucket.Acquire(1) { // 剩余空间是否大于1 fmt.Println("Request", i, "allowed at", time.Now()) } else { fmt.Println("Request", i, "rejected at", time.Now()) } time.Sleep(time.Second) } } ``` 上述示例中,我们创建了一个容量为10,每秒放入2个令牌的漏斗,并模拟了20个请求的到来。在每个请求到来时,通过`bucket.Acquire(1)`方法来判断是否允许通过。运行结果如下: ``` Request 0 allowed at 2019-12-01 14:15:00.000 Request 1 allowed at 2019-12-01 14:15:01.000 ... Request 9 rejected at 2019-12-01 14:15:09.000 Request 10 allowed at 2019-12-01 14:15:10.000 ... ``` 从结果中可以看出,前10个请求都被允许通过,而第11个请求因为漏斗已满被拒绝。