distrubtLock.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package lock
  2. import (
  3. "context"
  4. "eta/eta_api/utils"
  5. "fmt"
  6. "github.com/go-redis/redis/v8"
  7. )
  8. const (
  9. lockName = "lock:"
  10. )
  11. var (
  12. ctx = context.Background()
  13. )
  14. func AcquireLock(key string, expiration int, Holder string) bool {
  15. script := redis.NewScript(`local key = KEYS[1]
  16. local clientId = ARGV[1]
  17. local expiration = tonumber(ARGV[2])
  18. if redis.call("EXISTS", key) == 0 then
  19. redis.call("SET", key, clientId, "EX", expiration)
  20. return 1
  21. else
  22. return 0
  23. end`)
  24. fmt.Println("lockName:"+lockName+key, "Holder:"+Holder, "expiration:"+fmt.Sprintf("%d", expiration))
  25. lockey := fmt.Sprintf("%s%s", lockName, key)
  26. result, err := script.Run(ctx, utils.Rc.RedisClient(), []string{lockey}, Holder, expiration).Int()
  27. if err != nil {
  28. fmt.Printf("加锁失败:err: %v", err)
  29. return false
  30. }
  31. if result == 1 {
  32. return true
  33. }
  34. fmt.Printf("加锁失败:")
  35. return false
  36. }
  37. func ReleaseLock(key string, holder string) bool {
  38. script := redis.NewScript(`
  39. if redis.call("get", KEYS[1]) == ARGV[1] then
  40. return redis.call("del", KEYS[1])
  41. else
  42. return 0
  43. end
  44. `)
  45. fmt.Println("lockName:"+lockName+key, "Holder:"+holder)
  46. lockey := fmt.Sprintf("%s%s", lockName, key)
  47. result, err := script.Run(ctx, utils.Rc.RedisClient(), []string{lockey}, holder).Int()
  48. if err != nil {
  49. fmt.Printf("解锁失败:err: %v", err)
  50. return false
  51. }
  52. if result == 1 {
  53. return true
  54. }
  55. fmt.Printf("解锁失败:")
  56. return false
  57. }