localcache.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package dao
  2. import (
  3. "context"
  4. "time"
  5. "go-common/app/service/main/relation/model"
  6. "go-common/library/log"
  7. "go-common/library/stat/prom"
  8. "github.com/bluele/gcache"
  9. "github.com/pkg/errors"
  10. )
  11. func (d *Dao) loadStat(ctx context.Context, mid int64) (*model.Stat, error) {
  12. stat, err := d.statCache(ctx, mid)
  13. if err != nil {
  14. return nil, err
  15. }
  16. d.storeStat(mid, stat)
  17. return stat, nil
  18. }
  19. func (d *Dao) storeStat(mid int64, stat *model.Stat) {
  20. if stat == nil || stat.Follower < int64(d.c.StatCache.LeastFollower) {
  21. return
  22. }
  23. d.statStore.SetWithExpire(mid, stat, time.Duration(d.c.StatCache.Expire))
  24. }
  25. func (d *Dao) localStat(mid int64) (*model.Stat, error) {
  26. prom.CacheHit.Incr("local_stat_cache")
  27. item, err := d.statStore.Get(mid)
  28. if err != nil {
  29. prom.CacheMiss.Incr("local_stat_cache")
  30. return nil, err
  31. }
  32. stat, ok := item.(*model.Stat)
  33. if !ok {
  34. prom.CacheMiss.Incr("local_stat_cache")
  35. return nil, errors.New("Not a stat")
  36. }
  37. return stat, nil
  38. }
  39. // StatCache get stat cache.
  40. func (d *Dao) StatCache(c context.Context, mid int64) (*model.Stat, error) {
  41. stat, err := d.localStat(mid)
  42. if err != nil {
  43. if err != gcache.KeyNotFoundError {
  44. log.Error("Failed to get stat from local: mid: %d: %+v", mid, err)
  45. }
  46. return d.loadStat(c, mid)
  47. }
  48. return stat, nil
  49. }
  50. // StatsCache get multi stat cache.
  51. func (d *Dao) StatsCache(c context.Context, mids []int64) (map[int64]*model.Stat, []int64, error) {
  52. stats := make(map[int64]*model.Stat, len(mids))
  53. lcMissed := make([]int64, 0, len(mids))
  54. for _, mid := range mids {
  55. stat, err := d.localStat(mid)
  56. if err != nil {
  57. if err != gcache.KeyNotFoundError {
  58. log.Error("Failed to get stat from local: mid: %d: %+v", mid, err)
  59. }
  60. lcMissed = append(lcMissed, mid)
  61. continue
  62. }
  63. stats[stat.Mid] = stat
  64. }
  65. if len(lcMissed) == 0 {
  66. return stats, nil, nil
  67. }
  68. mcStats, mcMissed, err := d.statsCache(c, lcMissed)
  69. if err != nil {
  70. return nil, nil, err
  71. }
  72. for _, stat := range mcStats {
  73. d.storeStat(stat.Mid, stat)
  74. stats[stat.Mid] = stat
  75. }
  76. return stats, mcMissed, nil
  77. }