memcache.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package dao
  2. import (
  3. "context"
  4. "fmt"
  5. "go-common/library/cache/memcache"
  6. "go-common/library/log"
  7. )
  8. const (
  9. _partitionKey = "p_%s_%d"
  10. )
  11. // pingMC ping memcache.
  12. func (d *Dao) pingMC(ctx context.Context) (err error) {
  13. conn := d.mc.Get(ctx)
  14. defer conn.Close()
  15. if err = conn.Set(&memcache.Item{Key: "ping", Value: []byte{1}, Expiration: 0}); err != nil {
  16. log.Error("conn.Store(set,ping,1) error(%v)", err)
  17. }
  18. return
  19. }
  20. func partitionCacheKey(e string, p int32) string {
  21. return fmt.Sprintf(_partitionKey, e, p)
  22. }
  23. // OffsetCache .
  24. func (d *Dao) OffsetCache(ctx context.Context, event string, p int32) (offset int64, err error) {
  25. var (
  26. key = partitionCacheKey(event, p)
  27. conn = d.mc.Get(ctx)
  28. )
  29. defer conn.Close()
  30. reply, err := conn.Get(key)
  31. if err != nil {
  32. if err == memcache.ErrNotFound {
  33. err = nil
  34. return
  35. }
  36. log.Error("conn.Get(get,%d) error(%v)", p, err)
  37. return
  38. }
  39. if err = conn.Scan(reply, &offset); err != nil {
  40. log.Error("reply.Scan(%s) error(%v)", string(reply.Value), err)
  41. }
  42. return
  43. }
  44. // SetOffsetCache .
  45. func (d *Dao) SetOffsetCache(ctx context.Context, event string, p int32, offset int64) (err error) {
  46. var (
  47. key = partitionCacheKey(event, p)
  48. conn = d.mc.Get(ctx)
  49. )
  50. defer conn.Close()
  51. if err = conn.Set(&memcache.Item{Key: key, Object: offset, Expiration: 0, Flags: memcache.FlagJSON}); err != nil {
  52. log.Error("conn.Set(%s,%d) error(%v)", key, offset, err)
  53. }
  54. return
  55. }