document_cache.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package dao
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. mc "go-common/library/cache/memcache"
  7. "go-common/library/log"
  8. )
  9. const (
  10. _docKeyPrefix = "d"
  11. )
  12. // pingMemcache check memcache health
  13. func (d *Dao) pingMemcache(ctx context.Context) (err error) {
  14. conn := d.cache.Get(ctx)
  15. item := mc.Item{Key: "ping", Value: []byte{1}, Expiration: d.mcExpire}
  16. err = conn.Set(&item)
  17. conn.Close()
  18. return
  19. }
  20. // DocumentCache memcache get document(hash)
  21. func (d *Dao) DocumentCache(ctx context.Context, checkSum int64) (data json.RawMessage, err error) {
  22. var result *mc.Item
  23. conn := d.cache.Get(ctx)
  24. defer conn.Close()
  25. if result, err = conn.Get(cacheDocKey(checkSum)); err != nil {
  26. if err == mc.ErrNotFound {
  27. err = nil
  28. return
  29. }
  30. log.Error("conn.Get(%s) error(%v)", cacheDocKey(checkSum), err)
  31. return
  32. }
  33. data = json.RawMessage(result.Value)
  34. return
  35. }
  36. // DelDocumentCache remove memcache document detail
  37. func (d *Dao) DelDocumentCache(ctx context.Context, checkSum int64) (err error) {
  38. conn := d.cache.Get(ctx)
  39. defer conn.Close()
  40. if err = conn.Delete(cacheDocKey(checkSum)); err == mc.ErrNotFound {
  41. err = nil
  42. }
  43. return
  44. }
  45. // SetDocumentCache add document cache
  46. func (d *Dao) SetDocumentCache(ctx context.Context, checkSum int64, data json.RawMessage) (err error) {
  47. conn := d.cache.Get(ctx)
  48. defer conn.Close()
  49. if err = conn.Set(&mc.Item{
  50. Key: cacheDocKey(checkSum),
  51. Value: data,
  52. Expiration: d.mcExpire,
  53. }); err != nil {
  54. log.Error("dao.SetDocumentCache(%v,%s) err:%v", cacheDocKey(checkSum), data, err)
  55. return
  56. }
  57. return
  58. }
  59. func cacheDocKey(checkSum int64) string {
  60. return fmt.Sprintf("%v_%v", _docKeyPrefix, checkSum)
  61. }