distrubtLock.go 1.2 KB

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