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