redis_lock.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package cache
  4. import (
  5. "sync"
  6. "time"
  7. )
  8. type Lock struct {
  9. Key string
  10. Ttl int64
  11. stop bool
  12. mutex sync.Mutex
  13. }
  14. // 监听过期
  15. func (lock *Lock) watchLock() {
  16. sleepTime := time.Duration(lock.Ttl * 2 / 3)
  17. for {
  18. time.Sleep(sleepTime * time.Second)
  19. lock.mutex.Lock()
  20. if lock.stop {
  21. lock.mutex.Unlock()
  22. return
  23. }
  24. redisCache.Expire(lock.Key, lock.Ttl)
  25. lock.mutex.Unlock()
  26. }
  27. }
  28. func (lock *Lock) stopWatch() {
  29. lock.stop = true
  30. }
  31. func (lock *Lock) RedisLock() bool {
  32. if lock.Key == "" {
  33. return false
  34. }
  35. res, err := redisCache.SetNxEx(lock.Key, "lock", lock.Ttl)
  36. // redis 操作失败
  37. if err != nil {
  38. return false
  39. }
  40. // 上锁成功
  41. if res {
  42. go lock.watchLock()
  43. return true
  44. }
  45. return false
  46. }
  47. func (lock *Lock) RedisUnlock() {
  48. // 释放分布式锁
  49. lock.mutex.Lock()
  50. defer lock.mutex.Unlock()
  51. lock.stopWatch()
  52. redisCache.Del(lock.Key)
  53. }
  54. func RedisLock(key string) bool {
  55. res, err := redisCache.SetNxEx(key, "lock", 60)
  56. // redis 操作失败
  57. if err != nil {
  58. return false
  59. }
  60. // 上锁成功
  61. if res {
  62. return true
  63. }
  64. return false
  65. }
  66. func RedisUnlock(key string) {
  67. // 释放分布式锁
  68. redisCache.Del(key)
  69. }