欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

解決python-redis-lock分布式鎖的問(wèn)題

 更新時(shí)間:2021年10月31日 10:32:19   作者:Loganer  
這篇文章主要介紹了python-redis-lock分布式鎖的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

python-redis-lock

官方文檔
不錯(cuò)的博文可參考

問(wèn)題背景

在使用celery執(zhí)行我們的異步任務(wù)時(shí),為了提高效率,celery可以開(kāi)啟多個(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è)沒(méi)插入時(shí),另一個(gè)也掃描完了數(shù)據(jù)庫(kù),這時(shí)這兩個(gè)worker都會(huì)認(rèn)為自己拿到的UUID是在數(shù)據(jù)庫(kù)中沒(méi)有存在過(guò)的,所以都會(huì)調(diào)用INSERT方法來(lái)進(jìn)行插入操作。

幾種解決方案

為了解決這個(gè)問(wèn)題,一般有如下解決方案.
分布式鎖家族:

數(shù)據(jù)庫(kù):

  • 排它鎖(悲觀鎖)
  • 樂(lè)觀鎖

Redis

  1. 自己實(shí)現(xiàn)Redis SET SETNX 操作,結(jié)合Lua腳本確保原子操作
  2. RedLock Redis里分布式鎖實(shí)現(xiàn)的算法,爭(zhēng)議比較大,謹(jǐn)慎使用
  3. python-redis-lock 本文將要介紹的技術(shù)。這個(gè)庫(kù)提供的分布式鎖很靈活,是否需要超時(shí)?是否需要自動(dòng)刷新?是否要阻塞?都是可選的。沒(méi)有最好的算法,只有最合適的算法,開(kāi)發(fā)人員應(yīng)該根據(jù)實(shí)際需求場(chǎng)景謹(jǐn)慎選擇具體用哪一種技術(shù)去實(shí)現(xiàn)。

設(shè)計(jì)思路:

來(lái)自官網(wǎng) 

Zookeeper
這個(gè)應(yīng)該是功能最強(qiáng)大的,比較專(zhuān)業(yè),穩(wěn)定性好。我還沒(méi)使用過(guò),日后玩明白了再寫(xiě)篇文章總結(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)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論