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