日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

python 分布式锁_python分布式锁

發布時間:2025/3/13 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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分布式锁的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。