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.

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
1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package redis_lock
  2. import (
  3. "code.gitea.io/gitea/modules/redis/redis_client"
  4. "time"
  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 {
  13. isOk, _ := redis_client.Setnx(lock.lockKey, "", expireTime)
  14. return isOk
  15. }
  16. func (lock *DistributeLock) LockWithWait(expireTime time.Duration, waitTime time.Duration) bool {
  17. start := time.Now().Unix() * 1000
  18. duration := waitTime.Milliseconds()
  19. for {
  20. isOk, _ := redis_client.Setnx(lock.lockKey, "", expireTime)
  21. if isOk {
  22. return true
  23. }
  24. if time.Now().Unix()*1000-start > duration {
  25. return false
  26. }
  27. time.Sleep(50 * time.Millisecond)
  28. }
  29. return false
  30. }
  31. func (lock *DistributeLock) UnLock() error {
  32. _, err := redis_client.Del(lock.lockKey)
  33. return err
  34. }