reqLimit.go 849 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. func (r *ReqLimit) Init() {
  11. if ok, err := redis.Exists("other", r.Key); err != nil || ok {
  12. return
  13. }
  14. for i := 0; i < r.Size; i++ {
  15. redis.RPUSH("other", r.Key, 1)
  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. func (r *ReqLimit) UnLimit() {
  37. if r.Size <= 0 {
  38. return
  39. }
  40. if int(redis.LLEN("other", r.Key)) < r.Size {
  41. redis.RPUSH("other", r.Key, 1)
  42. }
  43. }