当前位置:   article > 正文

Golang速率限制_golang 限速

golang 限速

rate-limiting.go

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. requests := make(chan int, 5)
  8. for i := 1; i <= 5; i++ {
  9. requests <- i
  10. }
  11. close(requests)
  12. limiter := time.Tick(200 * time.Millisecond)
  13. for req := range requests {
  14. <-limiter
  15. fmt.Println("request", req, time.Now())
  16. }
  17. burstyLimiter := make(chan time.Time, 3)
  18. for i := 0; i < 3; i++ {
  19. burstyLimiter <- time.Now()
  20. }
  21. go func() {
  22. for t := range time.Tick(200 * time.Millisecond) {
  23. burstyLimiter <- t
  24. }
  25. }()
  26. burstyRequest := make(chan int, 5)
  27. for i := 1; i <= 5; i++ {
  28. burstyRequest <- i
  29. }
  30. close(burstyRequest)
  31. for req := range burstyRequest {
  32. <-burstyLimiter
  33. fmt.Println("request", req, time.Now())
  34. }
  35. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/230058
推荐阅读
  

闽ICP备14008679号