service.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "sync"
  7. "go-common/app/job/live/gift/internal/model"
  8. "go-common/library/log"
  9. "go-common/library/queue/databus"
  10. pb "go-common/app/job/live/gift/api"
  11. "go-common/app/job/live/gift/internal/conf"
  12. "go-common/app/job/live/gift/internal/dao"
  13. "github.com/golang/protobuf/ptypes/empty"
  14. )
  15. // Service struct
  16. type Service struct {
  17. c *conf.Config
  18. dao *dao.Dao
  19. addFreeGift *databus.Databus
  20. waiter sync.WaitGroup
  21. }
  22. // New init
  23. func New(c *conf.Config) (s *Service) {
  24. s = &Service{
  25. c: c,
  26. dao: dao.New(c),
  27. addFreeGift: databus.New(c.Databus.AddGift),
  28. }
  29. go s.infocproc()
  30. for i := 0; i < c.Consumer.AddGift.Num; i++ {
  31. s.waiter.Add(1)
  32. go s.addGiftConsumeProc()
  33. }
  34. return s
  35. }
  36. func (s *Service) addGiftConsumeProc() {
  37. defer s.waiter.Done()
  38. var err error
  39. for {
  40. msg, ok := <-s.addFreeGift.Messages()
  41. if !ok {
  42. log.Error("s.addFreeGift.Messages channel closed")
  43. return
  44. }
  45. m := &model.AddFreeGift{}
  46. if err = json.Unmarshal(msg.Value, &m); err != nil {
  47. log.Error("json.Unmarshal(%v) error(%v)", msg, err)
  48. continue
  49. }
  50. ctx := context.Background()
  51. // 消息幂等
  52. if m.MsgID != "" {
  53. key := m.MsgID + m.Source
  54. gotLock, _, errLock := s.dao.Lock(ctx, key, 3600000, 0, 0)
  55. if errLock != nil {
  56. continue
  57. }
  58. if !gotLock {
  59. log.Error("msg has been processed,%v", m)
  60. continue
  61. }
  62. }
  63. s.AddGift(ctx, m)
  64. // 打点上报
  65. s.giftActionInfoc(m.UID, 0, m.GiftID, 0, m.GiftNum, m.Source, "")
  66. log.Info("consume addFreeGift topic:%s, Key:%s, Value:%s ", msg.Topic, msg.Key, msg.Value)
  67. if err = msg.Commit(); err != nil {
  68. log.Error("commit msg(%v) error(%v)", msg, err)
  69. }
  70. }
  71. }
  72. // SayHello grpc demo func
  73. func (s *Service) SayHello(ctx context.Context, req *pb.HelloReq) (reply *empty.Empty, err error) {
  74. reply = new(empty.Empty)
  75. fmt.Printf("hello %s", req.Name)
  76. return
  77. }
  78. // Ping Service
  79. func (s *Service) Ping(ctx context.Context) (err error) {
  80. return s.dao.Ping(ctx)
  81. }
  82. // Close Service
  83. func (s *Service) Close() {
  84. s.dao.Close()
  85. }