limit.go 923 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package utility
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/os/gctx"
  5. "time"
  6. )
  7. var (
  8. cxt = gctx.New()
  9. JySeoQueryListLimit *limit = InitLimit(g.Cfg().MustGet(cxt, "queryLimit.listPool", 10).Int(), g.Cfg().MustGet(cxt, "queryLimit.timeout", 5).Int())
  10. JySeoQueryTabLimit *limit = InitLimit(g.Cfg().MustGet(cxt, "queryLimit.tabPool", 10).Int(), g.Cfg().MustGet(cxt, "queryLimit.timeout", 5).Int())
  11. )
  12. type (
  13. limit struct {
  14. pool chan struct{}
  15. timeOut time.Duration
  16. }
  17. )
  18. func InitLimit(poolNum, timeOut int) *limit {
  19. p := make(chan struct{}, poolNum)
  20. for i := 0; i < poolNum; i++ {
  21. p <- struct{}{}
  22. }
  23. return &limit{
  24. pool: p,
  25. timeOut: time.Second * time.Duration(timeOut),
  26. }
  27. }
  28. func (l *limit) Limit() bool {
  29. select {
  30. case <-l.pool:
  31. return true
  32. case <-time.After(time.Second * 5):
  33. return false
  34. }
  35. }
  36. func (l *limit) Reset() {
  37. l.pool <- struct{}{}
  38. }