python分布式鎖
來源:懂視網(wǎng)
責(zé)編:小采
時間:2020-11-27 14:27:20
python分布式鎖
python分布式鎖:在進(jìn)行某些比較耗時的查詢時,為了避免進(jìn)行重復(fù)計算,可以采用分布式鎖服務(wù), 在同一個時間只有一個操作在進(jìn)行,同類的操作進(jìn)行等待重試. 下面的代碼(fetch_with_dist_lock)定義了一個fetcher,一個updater. 如果fetcher獲取不到數(shù)據(jù),則使用updater
導(dǎo)讀python分布式鎖:在進(jìn)行某些比較耗時的查詢時,為了避免進(jìn)行重復(fù)計算,可以采用分布式鎖服務(wù), 在同一個時間只有一個操作在進(jìn)行,同類的操作進(jìn)行等待重試. 下面的代碼(fetch_with_dist_lock)定義了一個fetcher,一個updater. 如果fetcher獲取不到數(shù)據(jù),則使用updater

在進(jìn)行某些比較耗時的查詢時,為了避免進(jìn)行重復(fù)計算,可以采用分布式鎖服務(wù),
在同一個時間只有一個操作在進(jìn)行,同類的操作進(jìn)行等待重試.
下面的代碼(fetch_with_dist_lock)定義了一個fetcher,一個updater.
如果fetcher獲取不到數(shù)據(jù),則使用updater進(jìn)行更新.更新成功之后通過fetcher返回結(jié)果.
也有一些情況,我們只想更新某個數(shù)據(jù),更新者是多個,但是更新操作不是原子的.那么
我們會通過update_with_dist_lock來進(jìn)行.
def fetch_with_dist_lock(mc_store, mutex_key, fetcher, updater,
lock_time=3*60*1000, sleep_time=100, retry_times=3):
i = 0
while i < retry_times:
i += 1
need_update, results = fetcher()
if need_update:
if(mc_store.add(mutex_key, lock_time)):
try:
updater()
continue
finally:
#release the distribute mutex anyway
mc_store.delete(mutex_key)
else:
time.sleep((sleep_time*1.0)/1000)
continue
return results
#too much tries, but failed still.
return None
def f_wrapper(f, *args, **kwargs):
def _():
return f(*args, **kwargs)
return _
def update_with_dist_lock(mc_store, mutex_key, updater, lock_time=60*1000, sleep_time=100, retry_times=5):
i = 0
while i < retry_times:
i += 1
if (mc_store.add(mutex_key, lock_time)):
try:
updater()
return True
finally:
mc_store.delete(mutex_key)
else:
time.sleep((sleep_time*1.0)/1000)
continue
return False
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com
python分布式鎖
python分布式鎖:在進(jìn)行某些比較耗時的查詢時,為了避免進(jìn)行重復(fù)計算,可以采用分布式鎖服務(wù), 在同一個時間只有一個操作在進(jìn)行,同類的操作進(jìn)行等待重試. 下面的代碼(fetch_with_dist_lock)定義了一個fetcher,一個updater. 如果fetcher獲取不到數(shù)據(jù),則使用updater