memcache.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package dao
  2. import (
  3. "context"
  4. "fmt"
  5. "go-common/app/service/main/point/model"
  6. gmc "go-common/library/cache/memcache"
  7. "github.com/pkg/errors"
  8. )
  9. const (
  10. _pointInfo = "pti:%d"
  11. )
  12. func pointKey(mid int64) string {
  13. return fmt.Sprintf(_pointInfo, mid)
  14. }
  15. //DelPointInfoCache .
  16. func (d *Dao) DelPointInfoCache(c context.Context, mid int64) (err error) {
  17. return d.delCache(c, pointKey(mid))
  18. }
  19. // PointInfoCache .
  20. func (d *Dao) PointInfoCache(c context.Context, mid int64) (pi *model.PointInfo, err error) {
  21. var (
  22. item *gmc.Item
  23. )
  24. key := pointKey(mid)
  25. conn := d.mc.Get(c)
  26. defer conn.Close()
  27. if item, err = conn.Get(key); err != nil {
  28. if err == gmc.ErrNotFound {
  29. err = nil
  30. pi = nil
  31. return
  32. }
  33. err = errors.Wrapf(err, "d.PointInfoCache(%d)", mid)
  34. d.errProm.Incr("get_mc")
  35. return
  36. }
  37. pi = new(model.PointInfo)
  38. if err = conn.Scan(item, pi); err != nil {
  39. err = errors.Wrapf(err, "conn.Scan(%d)", pi.Mid)
  40. d.errProm.Incr("scan_mc")
  41. }
  42. return
  43. }
  44. // SetPointInfoCache .
  45. func (d *Dao) SetPointInfoCache(c context.Context, pi *model.PointInfo) (err error) {
  46. key := pointKey(pi.Mid)
  47. conn := d.mc.Get(c)
  48. defer conn.Close()
  49. item := &gmc.Item{
  50. Key: key,
  51. Object: pi,
  52. Expiration: d.mcExpire,
  53. Flags: gmc.FlagJSON,
  54. }
  55. if err = conn.Set(item); err != nil {
  56. err = errors.Wrapf(err, "d.SetPointInfoCache(%d)", pi.Mid)
  57. d.errProm.Incr("set_mc")
  58. return
  59. }
  60. return
  61. }
  62. // DelCache del cache.
  63. func (d *Dao) delCache(c context.Context, key string) (err error) {
  64. conn := d.mc.Get(c)
  65. defer conn.Close()
  66. if err = conn.Delete(key); err != nil {
  67. if err == gmc.ErrNotFound {
  68. err = nil
  69. } else {
  70. err = errors.Wrapf(err, "conn.Delete(%s)", key)
  71. d.errProm.Incr("del_mc")
  72. }
  73. }
  74. return
  75. }