memcache.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package dao
  2. import (
  3. "context"
  4. "fmt"
  5. gmc "go-common/library/cache/memcache"
  6. "go-common/library/log"
  7. "github.com/pkg/errors"
  8. )
  9. const (
  10. _vipInfo = "big:%d"
  11. _ui = "ui:%s"
  12. )
  13. func userinfo(name string) string {
  14. return fmt.Sprintf(_ui, name)
  15. }
  16. func vipInfoKey(mid int64) string {
  17. return fmt.Sprintf(_vipInfo, mid)
  18. }
  19. // DelVipInfoCache delete vipinfo cache.
  20. func (d *Dao) DelVipInfoCache(c context.Context, mid int64) (err error) {
  21. return d.delCache(c, vipInfoKey(mid))
  22. }
  23. func (d *Dao) delCache(c context.Context, key string) (err error) {
  24. conn := d.mc.Get(c)
  25. defer conn.Close()
  26. if err = conn.Delete(key); err != nil {
  27. err = errors.WithStack(err)
  28. d.errProm.Incr("conn_del")
  29. return
  30. }
  31. return
  32. }
  33. // DelSelCode .
  34. func (d *Dao) DelSelCode(c context.Context, username string) (err error) {
  35. return d.delCache(c, userinfo(username))
  36. }
  37. // SetSelCode .
  38. func (d *Dao) SetSelCode(c context.Context, username string, linkmap map[int64]int64) (err error) {
  39. var (
  40. key = userinfo(username)
  41. )
  42. conn := d.mc.Get(c)
  43. defer conn.Close()
  44. item := &gmc.Item{Key: key, Object: linkmap, Expiration: d.mcExpire, Flags: gmc.FlagJSON}
  45. if err = conn.Set(item); err != nil {
  46. err = errors.Wrapf(err, "conn.Set(%s)", key)
  47. d.errProm.Incr("set_selcode")
  48. }
  49. return
  50. }
  51. // GetSelCode .
  52. func (d *Dao) GetSelCode(c context.Context, username string) (linkmap map[int64]int64, err error) {
  53. var (
  54. key = userinfo(username)
  55. )
  56. conn := d.mc.Get(c)
  57. defer conn.Close()
  58. item, err := conn.Get(key)
  59. if err != nil {
  60. if err == gmc.ErrNotFound {
  61. err = nil
  62. return
  63. }
  64. err = errors.Wrapf(err, "conn.Get(%s)", key)
  65. d.errProm.Incr("vipinfo_mc")
  66. return
  67. }
  68. linkmap = make(map[int64]int64)
  69. if err = conn.Scan(item, &linkmap); err != nil {
  70. err = errors.Wrapf(err, "conn.Scan(%s)", key)
  71. }
  72. return
  73. }
  74. // PingMC ping memcache.
  75. func (d *Dao) PingMC(c context.Context) (err error) {
  76. conn := d.mc.Get(c)
  77. defer conn.Close()
  78. if err = conn.Set(&gmc.Item{Key: "ping", Value: []byte{1}, Expiration: d.mcExpire}); err != nil {
  79. log.Error("conn.Store(set, ping, 1) error(%v)", err)
  80. }
  81. return
  82. }