package utils import ( "context" "fmt" ) const ( lockName = "lock:" ) var ( ctx = context.Background() ) func AcquireLock(key string, expiration int, holder string) bool { script := `local key = KEYS[1] local clientId = ARGV[1] local expiration = tonumber(ARGV[2]) if redis.call("EXISTS", key) == 0 then redis.call("SET", key, clientId, "EX", expiration) return 1 else return 0 end` lockey := fmt.Sprintf("%s%s", lockName, key) return Rc.RunLUA(script, ctx, []string{lockey}, holder, expiration) } func ReleaseLock(key string, holder string) bool { script := ` if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end ` lockey := fmt.Sprintf("%s%s", lockName, key) return Rc.RunLUA(script, ctx, []string{lockey}, holder) }