diff options
author | Andy McCurdy <andy@andymccurdy.com> | 2017-10-26 15:58:48 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-10-26 15:58:48 -0700 |
commit | a228945f1acaf5873dbb963360385198b3058ef3 (patch) | |
tree | 66715292f61417e6ce426fabefd319c4b74c6191 | |
parent | 25c46abdebbf60c599e6b9fcd7a4532bd8272a55 (diff) | |
parent | bb422881ffedf51710f96b29614f030ea71327f3 (diff) | |
download | redis-py-a228945f1acaf5873dbb963360385198b3058ef3.tar.gz |
Merge pull request #569 from 23doors/master
Atomic redis.set when acquiring a lock
-rw-r--r-- | redis/lock.py | 34 |
1 files changed, 6 insertions, 28 deletions
diff --git a/redis/lock.py b/redis/lock.py index 90f0e7a..732568b 100644 --- a/redis/lock.py +++ b/redis/lock.py @@ -118,11 +118,12 @@ class Lock(object): mod_time.sleep(sleep) def do_acquire(self, token): - if self.redis.setnx(self.name, token): - if self.timeout: - # convert to milliseconds - timeout = int(self.timeout * 1000) - self.redis.pexpire(self.name, timeout) + if self.timeout: + # convert to milliseconds + timeout = int(self.timeout * 1000) + else: + timeout = None + if self.redis.set(self.name, token, nx=True, px=timeout): return True return False @@ -188,25 +189,10 @@ class LuaLock(Lock): A lock implementation that uses Lua scripts rather than pipelines and watches. """ - lua_acquire = None lua_release = None lua_extend = None # KEYS[1] - lock name - # ARGV[1] - token - # ARGV[2] - timeout in milliseconds - # return 1 if lock was acquired, otherwise 0 - LUA_ACQUIRE_SCRIPT = """ - if redis.call('setnx', KEYS[1], ARGV[1]) == 1 then - if ARGV[2] ~= '' then - redis.call('pexpire', KEYS[1], ARGV[2]) - end - return 1 - end - return 0 - """ - - # KEYS[1] - lock name # ARGS[1] - token # return 1 if the lock was released, otherwise 0 LUA_RELEASE_SCRIPT = """ @@ -244,19 +230,11 @@ class LuaLock(Lock): @classmethod def register_scripts(cls, redis): - if cls.lua_acquire is None: - cls.lua_acquire = redis.register_script(cls.LUA_ACQUIRE_SCRIPT) if cls.lua_release is None: cls.lua_release = redis.register_script(cls.LUA_RELEASE_SCRIPT) if cls.lua_extend is None: cls.lua_extend = redis.register_script(cls.LUA_EXTEND_SCRIPT) - def do_acquire(self, token): - timeout = self.timeout and int(self.timeout * 1000) or '' - return bool(self.lua_acquire(keys=[self.name], - args=[token, timeout], - client=self.redis)) - def do_release(self, expected_token): if not bool(self.lua_release(keys=[self.name], args=[expected_token], |