Last active
November 30, 2018 04:21
-
-
Save DjaPy/c043260a2848d049c7c4b08e915e1945 to your computer and use it in GitHub Desktop.
Create distribution manager locker with python for redis.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import redis | |
import uuid | |
import time | |
import logging | |
CONN_SETTINGS = { | |
'host': 'localhost', | |
'port': 6379, | |
'db': 0, | |
} | |
def get_identifier(): | |
return str(uuid.uuid4()) | |
class Lock: | |
def __init__(self, redis_ins, my_key, identifier, timeout): | |
self.redis = redis_ins | |
self.timeout = timeout | |
self.my_key = my_key | |
self.identifier = identifier | |
def __enter__(self): | |
if self.acquire(timeout): | |
return self | |
def __exit__(self, exc_type, exc_value, traceback): | |
self.release() | |
def acquire(self, timeout): | |
end = time.time() + timeout | |
while end > time.time(): | |
status = self.redis.setnx(self.my_key, self.identifier) | |
if status: | |
return True | |
time.sleep(0.5) | |
assert RuntimeError, logging.debug('Unable to access key') | |
return False | |
def release(self): | |
pipe = redis.pipeline(True) | |
pipe.watch(self.my_key) | |
while True: | |
if pipe.get == self.identifier: | |
pipe.multi() | |
pipe.delete(self.my_key) | |
pipe.execute() | |
pipe.unwatch() | |
break | |
if __name__ == '__main__': | |
identifier = get_identifier() | |
my_key = 'search_something' | |
redis = redis.Redis(**CONN_SETTINGS) | |
timeout = 10 | |
locker = Lock(redis, my_key, identifier, timeout) | |
with locker: | |
time.sleep(10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment