stat.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package service
  2. import (
  3. "context"
  4. "go-common/app/interface/openplatform/article/dao"
  5. artmdl "go-common/app/interface/openplatform/article/model"
  6. "go-common/library/sync/errgroup"
  7. )
  8. // SetStat sets article's stat.
  9. func (s *Service) SetStat(c context.Context, aid int64, stat *artmdl.Stats) (err error) {
  10. group, ctx := errgroup.WithContext(c)
  11. group.Go(func() error {
  12. return s.dao.AddArticleStatsCache(ctx, aid, stat)
  13. })
  14. group.Go(func() error {
  15. s.SendMessage(ctx, aid, stat)
  16. return nil
  17. })
  18. err = group.Wait()
  19. return
  20. }
  21. func (s *Service) stat(c context.Context, aid int64) (res *artmdl.Stats, err error) {
  22. var addCache = true
  23. if res, err = s.dao.ArticleStatsCache(c, aid); err != nil {
  24. err = nil
  25. addCache = false
  26. } else if res != nil {
  27. return
  28. }
  29. res, err = s.dao.ArticleStats(c, aid)
  30. if res != nil && addCache {
  31. cache.Save(func() {
  32. s.dao.AddArticleStatsCache(context.TODO(), aid, res)
  33. })
  34. }
  35. return
  36. }
  37. func (s *Service) stats(c context.Context, aids []int64) (res map[int64]*artmdl.Stats, err error) {
  38. var (
  39. cachedArtStats map[int64]*artmdl.Stats
  40. missed []int64
  41. missedArtsStats map[int64]*artmdl.Stats
  42. addCache = true
  43. )
  44. if cachedArtStats, missed, err = s.dao.ArticlesStatsCache(c, aids); err != nil {
  45. addCache = false
  46. missed = aids
  47. err = nil
  48. }
  49. if len(missed) > 0 {
  50. if missedArtsStats, err = s.dao.ArticlesStats(c, missed); err != nil {
  51. addCache = false
  52. dao.PromError("stat:文章计数")
  53. err = nil
  54. }
  55. }
  56. res = make(map[int64]*artmdl.Stats)
  57. for aid, art := range cachedArtStats {
  58. res[aid] = art
  59. }
  60. if missedArtsStats == nil {
  61. missedArtsStats = make(map[int64]*artmdl.Stats)
  62. } else {
  63. for aid, art := range missedArtsStats {
  64. res[aid] = art
  65. }
  66. }
  67. if addCache {
  68. for _, aid := range aids {
  69. if _, ok := res[aid]; !ok {
  70. missedArtsStats[aid] = new(artmdl.Stats)
  71. }
  72. }
  73. cache.Save(func() {
  74. for id, stats := range missedArtsStats {
  75. s.dao.AddArticleStatsCache(context.TODO(), id, stats)
  76. }
  77. })
  78. }
  79. return
  80. }