redis實現(xiàn)分布式鎖主要使用redis單線程的對key原子操作特性财异,
以下代碼經(jīng)歷生產(chǎn)環(huán)境的實驗院刁,已經(jīng)在生產(chǎn)環(huán)境使用。
連接redis
redis_client = redis.Redis(host="localhost",
port=6379,
password=password,
db=10)
獲取一個鎖
lock_name:鎖定名稱
acquire_time: 客戶端等待獲取鎖的時間
time_out: 鎖的超時時間
def acquire_lock(lock_name, acquire_time=10, time_out=10):
"""獲取一個分布式鎖"""
identifier = str(uuid.uuid4())
end = time.time() + acquire_time
lock = "string:lock:" + lock_name
while time.time() < end:
if redis_client.setnx(lock, identifier):
# 給鎖設(shè)置超時時間, 防止進(jìn)程崩潰導(dǎo)致其他進(jìn)程無法獲取鎖
redis_client.expire(lock, time_out)
return identifier
elif not redis_client.ttl(lock):
redis_client.expire(lock, time_out)
time.sleep(0.001)
return False
釋放一個鎖
def release_lock(lock_name, identifier):
"""通用的鎖釋放函數(shù)"""
lock = "string:lock:" + lock_name
pip = redis_client.pipeline(True)
while True:
try:
pip.watch(lock)
lock_value = redis_client.get(lock)
if not lock_value:
return True
if lock_value.decode() == identifier:
pip.multi()
pip.delete(lock)
pip.execute()
return True
pip.unwatch()
break
except redis.excetions.WacthcError:
pass
return False
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者