python 分布式锁_python分布式锁
在進(jìn)行某些比較耗時(shí)的查詢時(shí),為了避免進(jìn)行重復(fù)計(jì)算,可以采用分布式鎖服務(wù),
在同一個(gè)時(shí)間只有一個(gè)操作在進(jìn)行,同類的操作進(jìn)行等待重試.
下面的代碼(fetch_with_dist_lock)定義了一個(gè)fetcher,一個(gè)updater.
如果fetcher獲取不到數(shù)據(jù),則使用updater進(jìn)行更新.更新成功之后通過fetcher返回結(jié)果.
也有一些情況,我們只想更新某個(gè)數(shù)據(jù),更新者是多個(gè),但是更新操作不是原子的.那么
我們會(huì)通過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
本文原創(chuàng)發(fā)布php中文網(wǎng),轉(zhuǎn)載請注明出處,感謝您的尊重!
總結(jié)
以上是生活随笔為你收集整理的python 分布式锁_python分布式锁的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: listview winfrom 表头_
- 下一篇: python教程怎么读_python怎么