memcache.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package dao
  2. import (
  3. "context"
  4. "encoding/json"
  5. "go-common/library/cache/memcache"
  6. "go-common/library/ecode"
  7. "go-common/library/log"
  8. )
  9. const (
  10. //appkeys represents key name
  11. _asspkeys = "sappkeys"
  12. )
  13. // pingMC ping memcache .
  14. func (d *Dao) pingMC(c context.Context) (err error) {
  15. conn := d.mc.Get(c)
  16. defer conn.Close()
  17. if err = conn.Set(&memcache.Item{Key: "ping", Value: []byte{1}, Expiration: 0}); err != nil {
  18. log.Error("conn.Store(set, ping, 1) error (%v)", err)
  19. }
  20. return
  21. }
  22. // AppkeyCache .
  23. func (d *Dao) AppkeyCache(c context.Context) (res map[string]string, err error) {
  24. var (
  25. conn memcache.Conn
  26. item *memcache.Item
  27. )
  28. conn = d.mc.Get(c)
  29. defer conn.Close()
  30. if item, err = conn.Get(_asspkeys); err != nil {
  31. if err == memcache.ErrNotFound {
  32. err = ecode.NothingFound
  33. }
  34. return
  35. }
  36. res = make(map[string]string)
  37. err = json.Unmarshal([]byte(item.Value), &res)
  38. return
  39. }
  40. // SetAppkeyCache .
  41. func (d *Dao) SetAppkeyCache(c context.Context, newData map[string]string) (err error) {
  42. var (
  43. conn memcache.Conn
  44. item *memcache.Item
  45. jsonAppCache []byte
  46. )
  47. if jsonAppCache, err = json.Marshal(newData); err != nil {
  48. return
  49. }
  50. conn = d.mc.Get(c)
  51. defer conn.Close()
  52. item = &memcache.Item{
  53. Key: _asspkeys,
  54. Value: jsonAppCache,
  55. }
  56. err = conn.Set(item)
  57. return
  58. }