mc.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package dao
  2. import (
  3. "context"
  4. "fmt"
  5. "go-common/app/job/main/reply-feed/model"
  6. "go-common/library/cache/memcache"
  7. "go-common/library/log"
  8. )
  9. const (
  10. _replyStatFormat = "rs_%d"
  11. )
  12. // PingMc ping
  13. func (d *Dao) PingMc(ctx context.Context) (err error) {
  14. conn := d.mc.Get(ctx)
  15. defer conn.Close()
  16. item := memcache.Item{Key: "ping", Value: []byte("pong"), Expiration: 0}
  17. return conn.Set(&item)
  18. }
  19. func keyReplyStat(rpID int64) string {
  20. return fmt.Sprintf(_replyStatFormat, rpID)
  21. }
  22. // RemReplyStatMc ...
  23. func (d *Dao) RemReplyStatMc(ctx context.Context, rpID int64) (err error) {
  24. conn := d.mc.Get(ctx)
  25. defer conn.Close()
  26. return conn.Delete(keyReplyStat(rpID))
  27. }
  28. // SetReplyStatMc set reply stat into mc.
  29. func (d *Dao) SetReplyStatMc(ctx context.Context, rs *model.ReplyStat) (err error) {
  30. conn := d.mc.Get(ctx)
  31. defer conn.Close()
  32. key := keyReplyStat(rs.RpID)
  33. item := &memcache.Item{
  34. Key: key,
  35. Object: rs,
  36. Expiration: d.mcExpire,
  37. Flags: memcache.FlagJSON,
  38. }
  39. if err = conn.Set(item); err != nil {
  40. log.Error("memcache Set(%s, %v), error(%v)", key, item, err)
  41. }
  42. return
  43. }
  44. // ReplyStatsMc get multi repies stat from memcache.
  45. func (d *Dao) ReplyStatsMc(ctx context.Context, rpIDs []int64) (rsMap map[int64]*model.ReplyStat, missIDs []int64, err error) {
  46. rsMap = make(map[int64]*model.ReplyStat)
  47. keys := make([]string, len(rpIDs))
  48. mapping := make(map[string]int64)
  49. for i, rpID := range rpIDs {
  50. key := keyReplyStat(rpID)
  51. keys[i] = key
  52. mapping[key] = rpID
  53. }
  54. for _, chunkedKeys := range splitString(keys, 2000) {
  55. var (
  56. conn = d.mc.Get(ctx)
  57. items map[string]*memcache.Item
  58. )
  59. if items, err = conn.GetMulti(chunkedKeys); err != nil {
  60. if err == memcache.ErrNotFound {
  61. missIDs = rpIDs
  62. err = nil
  63. conn.Close()
  64. return
  65. }
  66. conn.Close()
  67. log.Error("memcache GetMulti error(%v)", err)
  68. return
  69. }
  70. for _, item := range items {
  71. stat := new(model.ReplyStat)
  72. if err = conn.Scan(item, stat); err != nil {
  73. log.Error("memcache Scan(%v) error(%v)", item.Value, err)
  74. continue
  75. }
  76. rsMap[mapping[item.Key]] = stat
  77. delete(mapping, item.Key)
  78. }
  79. conn.Close()
  80. }
  81. for _, rpID := range mapping {
  82. missIDs = append(missIDs, rpID)
  83. }
  84. return
  85. }