好的,实现Redis分布式锁的Python代码如下:
import redis
import time
class RedisLock:
def __init__(self, redis_conn, lock_key, timeout=10):
self.redis = redis_conn
self.lock_key = lock_key
self.timeout = timeout
self.identifier = None
def acquire_lock(self):
identifier = str(time.time())
while True:
if self.redis.setnx(self.lock_key, identifier):
self.identifier = identifier
return True
current_value = self.redis.get(self.lock_key)
if not current_value:
continue
expiration_time = float(current_value) + self.timeout
if time.time() > expiration_time:
old_value = self.redis.getset(self.lock_key, identifier)
if old_value == current_value:
self.identifier = identifier
return True
time.sleep(0.1)
def release_lock(self):
pipe = self.redis.pipeline(True)
while True:
try:
pipe.watch(self.lock_key)
current_value = pipe.get(self.lock_key)
if not current_value:
break
if current_value.decode('utf-8') == self.identifier:
pipe.multi()
pipe.delete(self.lock_key)
pipe.execute()
return True
pipe.unwatch()
except redis.exceptions.WatchError:
pass
def __enter__(self):
result = self.acquire_lock()
if not result:
raise Exception("Could not obtain lock")
return result
def __exit__(self, type_, value, traceback):
result = self.release_lock()
使用方法如下所示:
redis_conn = redis.Redis(host='localhost', port=6379)
with RedisLock(redis_conn, 'my_lock'):
# 在此处执行需要加锁的代码
希望能够帮助到您。




