cache.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package guard
  2. import (
  3. "context"
  4. "fmt"
  5. "go-common/library/cache/redis"
  6. "go-common/library/log"
  7. )
  8. // redis cache
  9. const (
  10. _lockKey = "saveGuard:%s"
  11. _cacheKeyUid = "live_user:guard:uid:v1:%d"
  12. _cacheKeyTargetId = "live_user:guard:target_id:v1:%d"
  13. )
  14. // LockOrder lock for same order
  15. func (d *GuardDao) LockOrder(ctx context.Context, orderID string) (ok bool, err error) {
  16. conn := d.redis.Get(ctx)
  17. defer conn.Close()
  18. _, err = redis.String(conn.Do("SET", fmt.Sprintf(_lockKey, orderID), 1, "EX", 3*86400, "NX"))
  19. if err == redis.ErrNil {
  20. log.Info("LockOrder(%s) is ErrNil!", orderID)
  21. return false, nil
  22. }
  23. if err != nil {
  24. return false, err
  25. }
  26. return true, nil
  27. }
  28. // UnlockOrder release lock for same order
  29. func (d *GuardDao) UnlockOrder(ctx context.Context, orderID string) (err error) {
  30. conn := d.redis.Get(ctx)
  31. defer conn.Close()
  32. _, err = redis.String(conn.Do("DEL", fmt.Sprintf(_lockKey, orderID)))
  33. return
  34. }
  35. // ClearCache delete cache for guard
  36. func (d *GuardDao) ClearCache(ctx context.Context, uid int64, ruid int64) (err error) {
  37. conn := d.redis.Get(ctx)
  38. defer conn.Close()
  39. _, err = redis.String(conn.Do("DEL", fmt.Sprintf(_cacheKeyUid, uid)))
  40. _, err = redis.String(conn.Do("DEL", fmt.Sprintf(_cacheKeyTargetId, ruid)))
  41. return
  42. }