memcache.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package dao
  2. import (
  3. "context"
  4. "strconv"
  5. "go-common/app/service/main/secure/model"
  6. gmc "go-common/library/cache/memcache"
  7. "go-common/library/log"
  8. )
  9. const (
  10. _prefixLocs = "locs_"
  11. )
  12. func locsKey(mid int64) string {
  13. return _prefixLocs + strconv.FormatInt(mid, 10)
  14. }
  15. func (d *Dao) pingMC(c context.Context) (err error) {
  16. conn := d.mc.Get(c)
  17. if err = conn.Set(&gmc.Item{Key: "ping", Value: []byte{1}, Expiration: d.locsExpire}); err != nil {
  18. log.Error("conn.Store(set, ping, 1) error(%v)", err)
  19. }
  20. conn.Close()
  21. return
  22. }
  23. // AddLocsCache add login locs count to cache.
  24. func (d *Dao) AddLocsCache(c context.Context, mid int64, locs *model.Locs) (err error) {
  25. item := &gmc.Item{Key: locsKey(mid), Object: locs, Expiration: d.locsExpire, Flags: gmc.FlagProtobuf}
  26. conn := d.mc.Get(c)
  27. if err = conn.Set(item); err != nil {
  28. log.Error("AddLocs err(%v)", err)
  29. }
  30. conn.Close()
  31. return
  32. }
  33. // LocsCache get login locs count.
  34. func (d *Dao) LocsCache(c context.Context, mid int64) (locs map[int64]int64, err error) {
  35. conn := d.mc.Get(c)
  36. defer conn.Close()
  37. item, err := conn.Get(locsKey(mid))
  38. if err != nil {
  39. if err == gmc.ErrNotFound {
  40. err = nil
  41. }
  42. return
  43. }
  44. loc := &model.Locs{}
  45. if err = conn.Scan(item, loc); err != nil {
  46. log.Error("Locs err(%v)", err)
  47. }
  48. locs = loc.LocsCount
  49. return
  50. }