distrubtLock.go 836 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package utils
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. const (
  7. lockName = "lock:"
  8. )
  9. var (
  10. ctx = context.Background()
  11. )
  12. func AcquireLock(key string, expiration int, holder string) bool {
  13. script := `local key = KEYS[1]
  14. local clientId = ARGV[1]
  15. local expiration = tonumber(ARGV[2])
  16. if redis.call("EXISTS", key) == 0 then
  17. redis.call("SET", key, clientId, "EX", expiration)
  18. return 1
  19. else
  20. return 0
  21. end`
  22. lockey := fmt.Sprintf("%s%s", lockName, key)
  23. return Rc.RunLUA(script, ctx, []string{lockey}, holder, expiration)
  24. }
  25. func ReleaseLock(key string, holder string) bool {
  26. script := `
  27. if redis.call("get", KEYS[1]) == ARGV[1] then
  28. return redis.call("del", KEYS[1])
  29. else
  30. return 0
  31. end
  32. `
  33. lockey := fmt.Sprintf("%s%s", lockName, key)
  34. return Rc.RunLUA(script, ctx, []string{lockey}, holder)
  35. }