使用redis实现分布式锁

class RedisDistributedLock(object):
def __init__(self):
self.redis_cli = distributed_lock_redis_client(timeout=1)
self.lock_timeout = 10
self.lock_key = "random_lock_key"
self.now = long(time.time())
self.timestamp = self.now + self.lock_timeout

def getLock(self):
try:
lock = self.redis_cli.setnx(self.lock_key, self.timestamp)
if lock == True:
return True

last_timestamp = self.redis_cli.get(self.lock_key)
if last_timestamp and long(last_timestamp) <= self.now:
self.redis_cli.getset(self.lock_key, self.timestamp)
return True
return False
except Exception, ex:
logger.exception("[RedisDistributedLock] getLock fail error=%s" % ex)


def releaseLock(self):
try:
last_timestamp = self.redis_cli.get(self.lock_key)
if last_timestamp and long(last_timestamp) == self.timestamp:
self.redis_cli.delete(self.lock_key)
except Exception, ex:
logger.exception("[RedisDistributedLock] releaseLock fail error=%s" % ex)
原文地址:https://www.cnblogs.com/acvc/p/5926468.html