Skip to content

Instantly share code, notes, and snippets.

@zhyq0826
Last active August 18, 2016 10:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhyq0826/5e474f42c8167ab32a6627ddd837fc83 to your computer and use it in GitHub Desktop.
Save zhyq0826/5e474f42c8167ab32a6627ddd837fc83 to your computer and use it in GitHub Desktop.
python code for redis lock
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