package.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "go-common/app/job/live/gift/internal/model"
  6. "go-common/library/log"
  7. "go-common/library/sync/errgroup"
  8. )
  9. // AddGift AddGift
  10. func (s *Service) AddGift(ctx context.Context, m *model.AddFreeGift) (bagId int64, err error) {
  11. uid := m.UID
  12. giftID := m.GiftID
  13. giftNum := m.GiftNum
  14. expireAt := m.ExpireAt
  15. source := m.Source
  16. if uid == 0 || giftID == 0 || giftNum == 0 {
  17. log.Error("add gift params error,uid:%d,giftID:%d,giftNum:%d", uid, giftID, giftNum)
  18. err = errors.New("params error")
  19. return
  20. }
  21. bagID, err := s.GetBagID(ctx, uid, giftID, expireAt)
  22. if err != nil {
  23. return
  24. }
  25. var (
  26. affectNum int64
  27. isUpdate = false
  28. eg, _ = errgroup.WithContext(ctx)
  29. )
  30. if bagID != 0 {
  31. isUpdate = true
  32. affectNum, _ = s.dao.UpdateBagNum(ctx, uid, bagID, giftNum)
  33. } else {
  34. affectNum, _ = s.dao.AddBag(ctx, uid, giftID, giftNum, expireAt)
  35. bagID = affectNum
  36. eg.Go(
  37. func() error {
  38. s.dao.SetBagIDCache(ctx, uid, giftID, expireAt, bagID, 14400)
  39. return nil
  40. })
  41. }
  42. newNum := giftNum
  43. if affectNum > 0 {
  44. eg.Go(
  45. func() error {
  46. s.dao.ClearBagListCache(ctx, uid)
  47. return nil
  48. })
  49. if isUpdate {
  50. res, _ := s.dao.GetBagByID(ctx, uid, bagID)
  51. newNum = res.GiftNum
  52. //上报lancer TODO
  53. s.bagLogInfoc(uid, bagID, giftID, giftNum, newNum, source)
  54. }
  55. }
  56. // 更新免费礼物数量缓存
  57. eg.Go(
  58. func() error {
  59. s.UpdateFreeGiftCache(ctx, uid, giftID, expireAt, newNum)
  60. return nil
  61. })
  62. eg.Wait()
  63. return
  64. }
  65. // GetBagID GetBagID
  66. func (s *Service) GetBagID(ctx context.Context, uid, giftID, expireAt int64) (id int64, err error) {
  67. id, err = s.dao.GetBagIDCache(ctx, uid, giftID, expireAt)
  68. if err != nil {
  69. return
  70. }
  71. if id == 0 {
  72. //queryDB
  73. var r *model.BagInfo
  74. r, err = s.dao.GetBag(ctx, uid, giftID, expireAt)
  75. if err != nil {
  76. return
  77. }
  78. id = r.ID
  79. }
  80. // 缓存或数据库本身有,再更新缓存
  81. if id != 0 {
  82. s.dao.SetBagIDCache(ctx, uid, giftID, expireAt, id, 14400)
  83. }
  84. return
  85. }
  86. // UpdateFreeGiftCache UpdateFreeGiftCache
  87. func (s *Service) UpdateFreeGiftCache(ctx context.Context, uid, giftID, expireAt, num int64) {
  88. //giftInfo := s.GetGiftInfoByID(ctx, giftID)
  89. //if giftInfo.Id == 0 || giftInfo.Type != 3 {
  90. // return
  91. //}
  92. //s.dao.SetBagNumCache(ctx, uid, giftID, expireAt, num, 14400)
  93. }