解決python-redis-lock分布式鎖的問(wèn)題
python-redis-lock
官方文檔
不錯(cuò)的博文可參考
問(wèn)題背景
在使用celery執(zhí)行我們的異步任務(wù)時(shí),為了提高效率,celery可以開啟多個(gè)進(jìn)程來(lái)啟動(dòng)對(duì)應(yīng)的worker。
但是會(huì)出現(xiàn)這么一種情況:在獲取到數(shù)據(jù)源之后要對(duì)數(shù)據(jù)庫(kù)進(jìn)行掃描,根據(jù)UUID來(lái)斷定是插入還是更新,兩個(gè)worker 同時(shí) (相差0.001S)拿到了UUID但是在其中一個(gè)沒插入時(shí),另一個(gè)也掃描完了數(shù)據(jù)庫(kù),這時(shí)這兩個(gè)worker都會(huì)認(rèn)為自己拿到的UUID是在數(shù)據(jù)庫(kù)中沒有存在過(guò)的,所以都會(huì)調(diào)用INSERT方法來(lái)進(jìn)行插入操作。
幾種解決方案
為了解決這個(gè)問(wèn)題,一般有如下解決方案.
分布式鎖家族:
數(shù)據(jù)庫(kù):
- 排它鎖(悲觀鎖)
- 樂(lè)觀鎖
Redis
- 自己實(shí)現(xiàn)Redis SET SETNX 操作,結(jié)合Lua腳本確保原子操作
- RedLock Redis里分布式鎖實(shí)現(xiàn)的算法,爭(zhēng)議比較大,謹(jǐn)慎使用
- python-redis-lock 本文將要介紹的技術(shù)。這個(gè)庫(kù)提供的分布式鎖很靈活,是否需要超時(shí)?是否需要自動(dòng)刷新?是否要阻塞?都是可選的。沒有最好的算法,只有最合適的算法,開發(fā)人員應(yīng)該根據(jù)實(shí)際需求場(chǎng)景謹(jǐn)慎選擇具體用哪一種技術(shù)去實(shí)現(xiàn)。
設(shè)計(jì)思路:

Zookeeper
這個(gè)應(yīng)該是功能最強(qiáng)大的,比較專業(yè),穩(wěn)定性好。我還沒使用過(guò),日后玩明白了再寫篇文章總結(jié)一下。
擴(kuò)展思路
在celery的場(chǎng)景下也可以使用celery_once進(jìn)行任務(wù)去重操作, celery_once底層也是使用redis進(jìn)行實(shí)現(xiàn)的。
可以參考這篇
Talk is cheap, show me your code!
一個(gè)簡(jiǎn)單的demo
import random
import time
import threading
import redis_lock
import redis
HOST = 'YOUR IP LOCATE'
PORT = '6379'
PASSWORD = 'password'
def get_redis():
pool = redis.ConnectionPool(host=HOST, port=PORT, password=PASSWORD, decode_responses=True, db=2)
r = redis.Redis(connection_pool=pool)
return r
def ask_lock(uuid):
lock = redis_lock.Lock(get_redis(), uuid)
if lock.acquire(blocking=False):
print(" %s Got the lock." % uuid)
time.sleep(5)
lock.release()
print(" %s Release the lock." % uuid)
else:
print(" %s Someone else has the lock." % uuid)
def simulate():
for i in range(10):
id = random.randint(0, 5)
t = threading.Thread(target=ask_lock, args=(str(id)))
t.start()
simulate()
Output:
4 Got the lock.
5 Got the lock.
3 Got the lock.
5 Someone else has the lock.
5 Someone else has the lock.
2 Got the lock.
5 Someone else has the lock.
4 Someone else has the lock.
3 Someone else has the lock.
3 Someone else has the lock.
2 Release the lock.
5 Release the lock.
4 Release the lock.
3 Release the lock.
到此這篇關(guān)于python-redis-lock分布式鎖的文章就介紹到這了,更多相關(guān)python分布式鎖內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信