newBidding.go 941 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package entity
  2. import (
  3. "context"
  4. "sync"
  5. "time"
  6. )
  7. //并发限制
  8. type reqLimit struct {
  9. doPool chan struct{}
  10. waitPool chan struct{}
  11. }
  12. var (
  13. ReqLimitInit *reqLimit
  14. ReqLimitLock = &sync.Mutex{}
  15. )
  16. func NewLimit(num int) {
  17. doPool := make(chan struct{}, num)
  18. for i := 0; i < num; i++ {
  19. doPool <- struct{}{}
  20. }
  21. waitPool := make(chan struct{}, num)
  22. for i := 0; i < num; i++ {
  23. waitPool <- struct{}{}
  24. }
  25. ReqLimitInit = &reqLimit{
  26. doPool: doPool,
  27. waitPool: waitPool,
  28. }
  29. }
  30. // -2 等待池已满
  31. // -1 超时
  32. // 1:可以执行查询
  33. func (r *reqLimit) Limit(ctx context.Context) int {
  34. ctx, cancel := context.WithTimeout(ctx, 30*time.Second) //30秒
  35. defer cancel()
  36. select {
  37. case <-r.waitPool:
  38. defer func() {
  39. r.waitPool <- struct{}{}
  40. }()
  41. select {
  42. case <-r.doPool:
  43. return 1
  44. case <-ctx.Done(): //超时
  45. return -1
  46. }
  47. default:
  48. return -2
  49. }
  50. }
  51. func (r *reqLimit) Release() {
  52. r.doPool <- struct{}{}
  53. }