service.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package service
  2. import (
  3. "context"
  4. "math/rand"
  5. "time"
  6. "go-common/app/admin/main/coupon/conf"
  7. "go-common/app/admin/main/coupon/dao"
  8. "go-common/app/admin/main/coupon/model"
  9. courpc "go-common/app/service/main/coupon/rpc/client"
  10. "go-common/library/log"
  11. "go-common/library/sync/pipeline/fanout"
  12. )
  13. const (
  14. _maxSalaryCount = 100000
  15. _notLimitSalary = -1
  16. _maxretry = 3
  17. _lockseconds = 604800
  18. )
  19. // Service struct
  20. type Service struct {
  21. c *conf.Config
  22. dao *dao.Dao
  23. r *rand.Rand
  24. allAppInfo map[int64]string
  25. couRPC *courpc.Service
  26. // cache async del
  27. cache *fanout.Fanout
  28. // msg async send
  29. msgchan *fanout.Fanout
  30. }
  31. // New init
  32. func New(c *conf.Config) (s *Service) {
  33. s = &Service{
  34. c: c,
  35. dao: dao.New(c),
  36. r: rand.New(rand.NewSource(time.Now().Unix())),
  37. allAppInfo: make(map[int64]string),
  38. couRPC: courpc.New(c.RPCClient2.Coupon),
  39. // cache chan
  40. cache: fanout.New("cache", fanout.Worker(5), fanout.Buffer(1024)),
  41. // msg chan
  42. msgchan: fanout.New("cache", fanout.Worker(5), fanout.Buffer(10240)),
  43. }
  44. if err := s.loadappinfo(); err != nil {
  45. panic(err)
  46. }
  47. go s.loadappinfoproc()
  48. return s
  49. }
  50. // Ping Service
  51. func (s *Service) Ping(c context.Context) (err error) {
  52. return s.dao.Ping(c)
  53. }
  54. // Close Service
  55. func (s *Service) Close() {
  56. s.dao.Close()
  57. }
  58. func (s *Service) loadappinfo() (err error) {
  59. var (
  60. c = context.Background()
  61. as []*model.AppInfo
  62. )
  63. if as, err = s.dao.AllAppInfo(c); err != nil {
  64. log.Error("loadappinfo allappinfo error(%v)", err)
  65. return
  66. }
  67. tmp := make(map[int64]string, len(as))
  68. for _, v := range as {
  69. tmp[v.ID] = v.Name
  70. }
  71. s.allAppInfo = tmp
  72. log.Info("loadappinfo (%v) load success", tmp)
  73. return
  74. }
  75. func (s *Service) loadappinfoproc() {
  76. defer func() {
  77. if x := recover(); x != nil {
  78. log.Error("service.loadappinfoproc panic(%v)", x)
  79. go s.loadappinfoproc()
  80. log.Info("service.loadappinfoproc recover")
  81. }
  82. }()
  83. for {
  84. time.Sleep(time.Minute * 2)
  85. s.loadappinfo()
  86. }
  87. }