memcache.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package dao
  2. import (
  3. "context"
  4. "encoding/json"
  5. "strconv"
  6. "go-common/app/interface/main/web-feed/model"
  7. "go-common/library/cache/memcache"
  8. "go-common/library/log"
  9. )
  10. const (
  11. _prefixFeed = "f_"
  12. )
  13. func feedKey(mid int64) string {
  14. return _prefixFeed + strconv.FormatInt(mid, 10)
  15. }
  16. // pingMc ping memcache
  17. func (d *Dao) pingMC(c context.Context) (err error) {
  18. conn := d.mc.Get(c)
  19. defer conn.Close()
  20. item := memcache.Item{Key: "ping", Value: []byte{1}, Expiration: 0}
  21. err = conn.Set(&item)
  22. return
  23. }
  24. // FeedCache gets feed cache
  25. func (d *Dao) FeedCache(c context.Context, mid int64) (feeds []*model.Feed, err error) {
  26. PromInfo("backup-cache")
  27. var (
  28. reply *memcache.Item
  29. conn = d.mc.Get(c)
  30. key = feedKey(mid)
  31. )
  32. defer conn.Close()
  33. if reply, err = conn.Get(key); err != nil {
  34. if err == memcache.ErrNotFound {
  35. err = nil
  36. } else {
  37. PromError("mc:获取feed缓存")
  38. log.Error("conn.Get(%s) error(%v)", key, err)
  39. }
  40. return
  41. }
  42. err = conn.Scan(reply, &feeds)
  43. return
  44. }
  45. // SetFeedCache sets feed cache
  46. func (d *Dao) SetFeedCache(c context.Context, mid int64, feeds []*model.Feed) (err error) {
  47. var (
  48. bs []byte
  49. key = feedKey(mid)
  50. conn = d.mc.Get(c)
  51. )
  52. defer conn.Close()
  53. if bs, err = json.Marshal(feeds); err != nil {
  54. PromError("mc:json feed缓存")
  55. log.Error("json.Marshal(%v) error(%v)", feeds, err)
  56. return
  57. }
  58. item := &memcache.Item{Key: key, Value: bs, Expiration: d.mcFeedExpire}
  59. if err = conn.Set(item); err != nil {
  60. PromError("mc:设置feed缓存")
  61. log.Error("conn.Set(%+v) error(%v)", item, err)
  62. }
  63. return
  64. }