memcache.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package recommend
  2. import (
  3. "context"
  4. "go-common/app/interface/main/app-card/model/card/ai"
  5. "go-common/library/cache/memcache"
  6. "github.com/pkg/errors"
  7. )
  8. const (
  9. _prefixRcmdAids = "rc"
  10. _prefixRcmd = "rc2"
  11. )
  12. func keyRcmdAids() string {
  13. return _prefixRcmdAids
  14. }
  15. func keyRcmd() string {
  16. return _prefixRcmd
  17. }
  18. // AddRcmdAidsCache add ai into cahce.
  19. func (d *Dao) AddRcmdAidsCache(c context.Context, aids []int64) (err error) {
  20. conn := d.mc.Get(c)
  21. key := keyRcmdAids()
  22. item := &memcache.Item{Key: key, Object: aids, Flags: memcache.FlagJSON, Expiration: d.expireMc}
  23. if err = conn.Set(item); err != nil {
  24. err = errors.Wrapf(err, "%v", aids)
  25. }
  26. conn.Close()
  27. return
  28. }
  29. // RcmdAidsCache get ai cache data from cache
  30. func (d *Dao) RcmdAidsCache(c context.Context) (aids []int64, err error) {
  31. var r *memcache.Item
  32. conn := d.mc.Get(c)
  33. key := keyRcmdAids()
  34. defer conn.Close()
  35. if r, err = conn.Get(key); err != nil {
  36. if err == memcache.ErrNotFound {
  37. err = nil
  38. return
  39. }
  40. err = errors.Wrap(err, key)
  41. return
  42. }
  43. if err = conn.Scan(r, &aids); err != nil {
  44. err = errors.Wrapf(err, "%s", r.Value)
  45. }
  46. return
  47. }
  48. // AddRcmdCache add ai into cahce.
  49. func (d *Dao) AddRcmdCache(c context.Context, is []*ai.Item) (err error) {
  50. conn := d.mc.Get(c)
  51. key := keyRcmd()
  52. item := &memcache.Item{Key: key, Object: is, Flags: memcache.FlagJSON, Expiration: d.expireMc}
  53. if err = conn.Set(item); err != nil {
  54. err = errors.Wrap(err, key)
  55. }
  56. conn.Close()
  57. return
  58. }
  59. // RcmdCache get ai cache data from cache
  60. func (d *Dao) RcmdCache(c context.Context) (is []*ai.Item, err error) {
  61. var r *memcache.Item
  62. conn := d.mc.Get(c)
  63. key := keyRcmd()
  64. defer conn.Close()
  65. if r, err = conn.Get(key); err != nil {
  66. if err == memcache.ErrNotFound {
  67. err = nil
  68. return
  69. }
  70. err = errors.Wrap(err, key)
  71. return
  72. }
  73. if err = conn.Scan(r, &is); err != nil {
  74. err = errors.Wrapf(err, "%s", r.Value)
  75. }
  76. return
  77. }