tokenlimit.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "runtime"
  6. "sync"
  7. "sync/atomic"
  8. "time"
  9. "github.com/tal-tech/go-zero/core/limit"
  10. "github.com/tal-tech/go-zero/core/stores/redis"
  11. )
  12. const (
  13. burst = 100
  14. rate = 100
  15. seconds = 5
  16. )
  17. var (
  18. rdx = flag.String("redis", "localhost:6379", "the redis, default localhost:6379")
  19. rdxType = flag.String("redisType", "node", "the redis type, default node")
  20. rdxKey = flag.String("redisKey", "rate", "the redis key, default rate")
  21. rdxPass = flag.String("redisPass", "", "the redis password")
  22. threads = flag.Int("threads", runtime.NumCPU(), "the concurrent threads, default to cores")
  23. )
  24. func main() {
  25. flag.Parse()
  26. store := redis.NewRedis(*rdx, *rdxType, *rdxPass)
  27. fmt.Println(store.Ping())
  28. limit := limit.NewTokenLimiter(rate, burst, store, *rdxKey)
  29. timer := time.NewTimer(time.Second * seconds)
  30. quit := make(chan struct{})
  31. defer timer.Stop()
  32. go func() {
  33. <-timer.C
  34. close(quit)
  35. }()
  36. var allowed, denied int32
  37. var wait sync.WaitGroup
  38. for i := 0; i < *threads; i++ {
  39. wait.Add(1)
  40. go func() {
  41. for {
  42. select {
  43. case <-quit:
  44. wait.Done()
  45. return
  46. default:
  47. if limit.Allow() {
  48. atomic.AddInt32(&allowed, 1)
  49. } else {
  50. atomic.AddInt32(&denied, 1)
  51. }
  52. }
  53. }
  54. }()
  55. }
  56. wait.Wait()
  57. fmt.Printf("allowed: %d, denied: %d, qps: %d\n", allowed, denied, (allowed+denied)/seconds)
  58. }