memcache.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package dao
  2. import (
  3. "context"
  4. "encoding/json"
  5. "go-common/library/conf/paladin"
  6. "time"
  7. "go-common/app/admin/main/workflow/model/search"
  8. "go-common/library/cache/memcache"
  9. "go-common/library/log"
  10. )
  11. const (
  12. _prefixChallPendingCount = "wkf_cpc_uid_%d"
  13. )
  14. // pingMC ping memcache.
  15. func (d *Dao) pingMC(c context.Context) (err error) {
  16. conn := d.mc.Get(c)
  17. //if err = conn.Store("set", "ping", []byte{1}, 0, d.mcExpire, 0); err != nil {
  18. if err = conn.Set(&memcache.Item{Key: "ping", Value: []byte{1}, Expiration: 0}); err != nil {
  19. log.Error("conn.Store(set, ping, 1) error(%v)", err)
  20. }
  21. conn.Close()
  22. return
  23. }
  24. // ChallCountCache read pending chall count by uid from memcache
  25. func (d *Dao) ChallCountCache(c context.Context, uid int64) (challCount *search.ChallCount, err error) {
  26. var (
  27. conn memcache.Conn
  28. item *memcache.Item
  29. key string
  30. )
  31. conn = d.mc.Get(c)
  32. defer conn.Close()
  33. key = d.keyChallCount(uid)
  34. if item, err = conn.Get(key); err != nil {
  35. if err == memcache.ErrNotFound {
  36. err = nil
  37. return
  38. }
  39. return
  40. }
  41. err = json.Unmarshal(item.Value, &challCount)
  42. return
  43. }
  44. // UpChallCountCache will write chall count to cache
  45. func (d *Dao) UpChallCountCache(c context.Context, challCount *search.ChallCount, uid int64) (err error) {
  46. var (
  47. conn memcache.Conn
  48. item *memcache.Item
  49. jsonChallCount []byte
  50. )
  51. jsonChallCount, err = json.Marshal(challCount)
  52. if err != nil {
  53. return
  54. }
  55. conn = d.mc.Get(c)
  56. defer conn.Close()
  57. item = &memcache.Item{
  58. Key: d.keyChallCount(uid),
  59. Value: jsonChallCount,
  60. Expiration: int32(paladin.Duration(d.c.Get("expireCount"), time.Duration(10*time.Second)) / time.Second),
  61. }
  62. err = conn.Set(item)
  63. return
  64. }