memcache.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package dao
  2. import (
  3. "context"
  4. "fmt"
  5. gmc "go-common/library/cache/memcache"
  6. "go-common/library/log"
  7. "github.com/pkg/errors"
  8. )
  9. const (
  10. _prefixCouponAllowances = "cas:%d:%d"
  11. _prefixCoupons = "cs:%d:%d"
  12. _prefixGrantUnique = "gu:%s"
  13. )
  14. func couponAllowancesKey(mid int64, state int8) string {
  15. return fmt.Sprintf(_prefixCouponAllowances, mid, state)
  16. }
  17. func couponsKey(mid int64, ct int8) string {
  18. return fmt.Sprintf(_prefixCoupons, ct, mid)
  19. }
  20. func grantUnique(token string) string {
  21. return fmt.Sprintf(_prefixGrantUnique, token)
  22. }
  23. // DelCouponAllowancesKey delete allowances cache.
  24. func (d *Dao) DelCouponAllowancesKey(c context.Context, mid int64, state int8) (err error) {
  25. return d.delCache(c, couponAllowancesKey(mid, state))
  26. }
  27. // DelCache del cache.
  28. func (d *Dao) delCache(c context.Context, key string) (err error) {
  29. conn := d.mc.Get(c)
  30. defer conn.Close()
  31. if err = conn.Delete(key); err != nil {
  32. if err == gmc.ErrNotFound {
  33. err = nil
  34. } else {
  35. err = errors.Wrapf(err, "mc.Delete(%s)", key)
  36. }
  37. }
  38. return
  39. }
  40. //DelCouponTypeCache del coupon.
  41. func (d *Dao) DelCouponTypeCache(c context.Context, mid int64, ct int8) (err error) {
  42. return d.delCache(c, couponsKey(mid, ct))
  43. }
  44. //DelGrantUniqueLock del lock.
  45. func (d *Dao) DelGrantUniqueLock(c context.Context, token string) (err error) {
  46. return d.delCache(c, grantUnique(token))
  47. }
  48. // AddGrantUniqueLock add grant coupon use lock.
  49. func (d *Dao) AddGrantUniqueLock(c context.Context, token string, seconds int32) (succeed bool) {
  50. var (
  51. key = grantUnique(token)
  52. conn = d.mc.Get(c)
  53. err error
  54. )
  55. defer conn.Close()
  56. item := &gmc.Item{
  57. Key: key,
  58. Value: []byte("0"),
  59. Expiration: seconds,
  60. }
  61. if err = conn.Add(item); err != nil {
  62. if err != gmc.ErrNotStored {
  63. log.Error("mc.Add(%s) error(%v)", key, err)
  64. }
  65. return
  66. }
  67. succeed = true
  68. return
  69. }