reqLimit.go 790 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package util
  2. import (
  3. "app.yhyue.com/moapp/jybase/redis"
  4. "github.com/gogf/gf/v2/util/gconv"
  5. )
  6. type ReqLimit struct {
  7. Key string
  8. Size int
  9. }
  10. //
  11. func (r *ReqLimit) Init() {
  12. r.Clear()
  13. for i := 0; i < r.Size; i++ {
  14. redis.RPUSH("other", r.Key, 1)
  15. }
  16. }
  17. //
  18. func (r *ReqLimit) Clear() {
  19. redis.Del("other", r.Key)
  20. }
  21. //查询是否被限流
  22. func (r *ReqLimit) IsLimit() bool {
  23. if r.Size <= 0 {
  24. return false
  25. }
  26. return redis.LLEN("other", r.Key) == 0
  27. }
  28. //并发数限制
  29. //return true 被限制 false 正常
  30. func (r *ReqLimit) Limit() bool {
  31. if r.Size <= 0 {
  32. return false
  33. }
  34. return gconv.Int64(redis.LPOP("other", r.Key)) <= 0
  35. }
  36. //
  37. func (r *ReqLimit) UnLimit() {
  38. if r.Size <= 0 {
  39. return
  40. }
  41. if int(redis.LLEN("other", r.Key)) < r.Size {
  42. redis.RPUSH("other", r.Key, 1)
  43. }
  44. }