天天看點

redis -- setnx 實作分布式鎖

SETNX key value

隻有在 key 不存在時設定 key 的值。存在的話,在執行後,傳回結果是0;不存在值,進行設定的話,傳回結果是1。

先用python實作兩個線程交替運作

import time
from threading import Thread

def task1():
    while True:
        print("this is task1")
        time.sleep(1)

def task2():
    while True:
        print("this is task2")
        time.sleep(1)

t1 = Thread(target=task1)
t2 = Thread(target=task2)
t1.start()
t2.start()
           

運作結果如下:

redis -- setnx 實作分布式鎖

現在用上多線程的互斥鎖

import time
from threading import Thread, Lock

i = 5

def task1():
    while True:
        global i
        i += 1
        if i % 3 == 0:
            print("this is task1", i)
            lock2.acquire()
            lock1.release()
            time.sleep(1)

def task2():
    while True:
        global i
        i += 1
        if i % 5 == 0:
            print("this is task2", i)
            lock1.acquire()
            lock2.release()
            time.sleep(1)

lock1 = Lock()
lock2 = Lock()
t1 = Thread(target=task1)
t2 = Thread(target=task2)
lock1.acquire()
t1.start()
t2.start()
           
redis -- setnx 實作分布式鎖

使用redis的setnx,可以實作分布式鎖的功能

import redis
import time
from threading import Thread, Lock

i = 5
res = redis.Redis(host='localhost', port=6379, db=9)

def task1():
    while True:
        global i
        i += 1
        res.delete("lock")
        if i % 3 == 0:
            if res.setnx("lock", "11"):
                print("this is task1", i)
                time.sleep(1)

def task2():
    while True:
        global i
        i += 1
        res.delete("lock")
        if i % 3 == 0:
            if res.setnx("lock", "11"):
                print("this is task2", i)
                time.sleep(1)

t1 = Thread(target=task1)
t2 = Thread(target=task2)
res.setnx("lock", "22")
t1.start()
t2.start()
           
redis -- setnx 實作分布式鎖

繼續閱讀