lock.go 676 B

1234567891011121314151617181920212223242526272829303132333435
  1. package utils
  2. import (
  3. "github.com/jaryhe/gopkgs/cache"
  4. "time"
  5. )
  6. const Prefix = "lock"
  7. // interval try lock时间间隔 ms, tryCount try lock 的次数
  8. func RedisLock(key string, interval int, tryCount int) (bool, error) {
  9. if interval <= 0 {
  10. interval = 500
  11. }
  12. if tryCount <= 0 {
  13. tryCount = 10
  14. }
  15. key = Prefix+"-"+key
  16. for i := 0; i < tryCount; i++ {
  17. ok, err := cache.Redis().SetNxEx(key, "-", 10)
  18. if err != nil {
  19. return false, err
  20. }
  21. if ok {
  22. return true, nil
  23. }
  24. time.Sleep(time.Duration(interval)*time.Microsecond)
  25. }
  26. return false, nil
  27. }
  28. func RedisUnlock(key string) error {
  29. key = Prefix+"-"+key
  30. _, err := cache.Redis().Del(key)
  31. return err
  32. }