cursor.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package history
  2. import (
  3. "context"
  4. "fmt"
  5. hismodel "go-common/app/interface/main/history/model"
  6. "go-common/app/interface/main/tv/model/history"
  7. "go-common/library/cache/memcache"
  8. "go-common/library/log"
  9. "go-common/library/net/metadata"
  10. "time"
  11. "github.com/pkg/errors"
  12. )
  13. func keyHis(mid int64) string {
  14. return fmt.Sprintf("tv_his_%d", mid)
  15. }
  16. // Cursor get history rpc data
  17. func (d *Dao) Cursor(c context.Context, mid, max int64, ps int, tp int8, businesses []string) (res []*hismodel.Resource, err error) {
  18. ip := metadata.String(c, metadata.RemoteIP)
  19. arg := &hismodel.ArgCursor{Mid: mid, Max: max, Ps: ps, RealIP: ip, TP: tp, ViewAt: max, Businesses: businesses}
  20. if res, err = d.hisRPC.HistoryCursor(c, arg); err != nil {
  21. err = errors.Wrapf(err, "d.historyRPC.HistoryCursor(%+v)", arg)
  22. }
  23. return
  24. }
  25. // HisCache get history cms cache.
  26. func (d *Dao) HisCache(c context.Context, mid int64) (s *history.HisMC, err error) {
  27. var (
  28. key = keyHis(mid)
  29. conn = d.mc.Get(c)
  30. item *memcache.Item
  31. )
  32. defer conn.Close()
  33. if item, err = conn.Get(key); err != nil {
  34. if err == memcache.ErrNotFound {
  35. err = nil
  36. missedCount.Add("tv-his", 1)
  37. } else {
  38. log.Error("conn.Get(%s) error(%v)", key, err)
  39. }
  40. return
  41. }
  42. if err = conn.Scan(item, &s); err != nil {
  43. log.Error("conn.Get(%s) error(%v)", key, err)
  44. }
  45. cachedCount.Add("tv-his", 1)
  46. return
  47. }
  48. // SaveHisCache save the member's history into cache
  49. func (d *Dao) SaveHisCache(ctx context.Context, filtered []*history.HisRes) {
  50. var hismc = &history.HisMC{}
  51. if len(filtered) == 0 {
  52. hismc.LastViewAt = time.Now().Unix()
  53. } else {
  54. firstItem := filtered[0]
  55. hismc.LastViewAt = firstItem.Unix
  56. hismc.MID = firstItem.Mid
  57. }
  58. hismc.Res = filtered
  59. d.addHisCache(ctx, hismc)
  60. }
  61. // addHisCache adds the history into cache
  62. func (d *Dao) addHisCache(ctx context.Context, his *history.HisMC) {
  63. d.addCache(func() {
  64. d.setHisCache(ctx, his)
  65. })
  66. }
  67. // setHisCache add his cache
  68. func (d *Dao) setHisCache(c context.Context, his *history.HisMC) (err error) {
  69. conn := d.mc.Get(c)
  70. defer conn.Close()
  71. item := &memcache.Item{Key: keyHis(his.MID), Object: his, Flags: memcache.FlagJSON, Expiration: d.expireHis}
  72. if err = conn.Set(item); err != nil {
  73. log.Error("conn.Store(%s) error(%v)", keyHis(his.MID), err)
  74. }
  75. log.Info("set HisMC Mid %d", his.MID)
  76. return
  77. }