shorturl_cache.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package dao
  2. import (
  3. "context"
  4. "go-common/app/interface/main/shorturl/model"
  5. "go-common/library/cache/memcache"
  6. "go-common/library/log"
  7. )
  8. func cacheKey(short string) string {
  9. return _prefix + short
  10. }
  11. // Cache get short url cache.
  12. func (d *Dao) Cache(c context.Context, short string) (su *model.ShortUrl, err error) {
  13. var (
  14. key = cacheKey(short)
  15. conn = d.memchDB.Get(c)
  16. item *memcache.Item
  17. )
  18. defer conn.Close()
  19. if item, err = conn.Get(key); err != nil {
  20. if err == memcache.ErrNotFound {
  21. err = nil
  22. } else {
  23. log.Error("conn.Get(%s) error(%v)", key, err)
  24. }
  25. return
  26. }
  27. if err = conn.Scan(item, &su); err != nil {
  28. log.Error("conn.Get(%s) error(%v)", key, err)
  29. }
  30. return
  31. }
  32. // SetEmptyCache set empty cache for a few time
  33. func (d *Dao) SetEmptyCache(c context.Context, short string) (err error) {
  34. var (
  35. key = cacheKey(short)
  36. conn = d.memchDB.Get(c)
  37. )
  38. defer conn.Close()
  39. if err = conn.Set(&memcache.Item{Key: key, Object: &model.ShortUrl{}, Flags: memcache.FlagJSON, Expiration: 300}); err != nil {
  40. log.Error("conn.Set error(%v)", err)
  41. }
  42. return
  43. }
  44. // SetCache save model.ShortUrl to memcache
  45. func (d *Dao) SetCache(c context.Context, su *model.ShortUrl) (err error) {
  46. var (
  47. key = cacheKey(su.Short)
  48. conn = d.memchDB.Get(c)
  49. )
  50. defer conn.Close()
  51. if err = conn.Set(&memcache.Item{Key: key, Object: su, Flags: memcache.FlagJSON, Expiration: 0}); err != nil {
  52. log.Error("conn.Set error(%v)", err)
  53. return
  54. }
  55. return
  56. }