You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

lock.go 1.0 kB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package redis_lock
  2. import (
  3. "time"
  4. "code.gitea.io/gitea/modules/redis/redis_client"
  5. )
  6. type DistributeLock struct {
  7. lockKey string
  8. }
  9. func NewDistributeLock(lockKey string) *DistributeLock {
  10. return &DistributeLock{lockKey: lockKey}
  11. }
  12. func (lock *DistributeLock) Lock(expireTime time.Duration) (bool, error) {
  13. isOk, err := redis_client.Setnx(lock.lockKey, "", expireTime)
  14. if err != nil {
  15. return false, err
  16. }
  17. return isOk, nil
  18. }
  19. func (lock *DistributeLock) LockWithWait(expireTime time.Duration, waitTime time.Duration) (bool, error) {
  20. start := time.Now().Unix() * 1000
  21. duration := waitTime.Milliseconds()
  22. for {
  23. isOk, err := redis_client.Setnx(lock.lockKey, "", expireTime)
  24. if err != nil {
  25. return false, err
  26. }
  27. if isOk {
  28. return true, nil
  29. }
  30. if time.Now().Unix()*1000-start > duration {
  31. return false, nil
  32. }
  33. time.Sleep(50 * time.Millisecond)
  34. }
  35. return false, nil
  36. }
  37. func (lock *DistributeLock) UnLock() error {
  38. _, err := redis_client.Del(lock.lockKey)
  39. return err
  40. }