Last active
August 18, 2016 10:07
-
-
Save zhyq0826/5e474f42c8167ab32a6627ddd837fc83 to your computer and use it in GitHub Desktop.
python code for redis lock
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 time | |
import redis | |
import logging | |
logger = logging.getLogger('service.redis_lock') | |
CONN = redis.Redis(host='localhost') | |
def acquire_lock(lockname, identifier, wait_time=20, timeout=15): | |
end = time.time() + wait_time | |
while end > time.time(): | |
if CONN.setnx(lockname, identifier): | |
CONN.expire(lockname, timeout) # set expire time | |
return identifier | |
time.sleep(0.001) #wait until the lock expired or release by some thread | |
return False | |
def release_lock(lockname, identifier): | |
pipe = CONN.pipeline(True) | |
try: | |
#watch lock once lock has been changed, break this transaction | |
pipe.watch(lockname) | |
#check if lock has been changed | |
if pipe.get(lockname) == identifier: | |
pipe.multi() | |
pipe.delete(lockname) | |
pipe.execute() | |
return True | |
pipe.unwatch() #execu when identifier not equal | |
except redis.exceptions.WatchError as e: | |
logger.error(e) | |
return False | |
except Exception as e: | |
logger.error(e) | |
return False | |
return False | |
if __name__ == '__main__': | |
print release_lock('h', 'a') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment