本文是一個demo,利用多進程,來模擬使用redis分佈式鎖的使用場景。本機須要安裝redis,python3.7下運行代碼。分佈式鎖用redlock這個包實現,實現步驟分三步:python
完整代碼以下:redis
# -*- coding: utf-8 -*- import os import arrow import redis from multiprocessing import Pool from redlock.lock import RedLock HOT_KEY = 'count' r = redis.Redis(host='localhost', port=6379) def seckilling(): name = os.getpid() v = r.get(HOT_KEY) if int(v) > 0: print (name, ' decr redis.') r.decr(HOT_KEY) else: print (name, ' can not set redis.', v) # def run_without_lock(name): while True: if arrow.now().second % 5 == 0: seckilling() return rlock = RedLock('test',[{'host': 'localhost','port': 6379,'db': 0,}]) def run_with_redis_lock(name): while True: if arrow.now().second % 5 == 0: # 二,獲取鎖 if rlock.acquire(): seckilling() # 釋放鎖 rlock.release() return if __name__ == '__main__': p = Pool(80) r.set(HOT_KEY, 1) for i in range(80): # p.apply_async(run_without_lock, args=(i,)) p.apply_async(run_with_redis_lock, args=(i,)) print ('now 16 processes are going to get lock!') p.close() p.join() print('All subprocesses done.')
使用鎖的代碼,主要是:併發
rlock = RedLock('test',[{'host': 'localhost','port': 6379,'db': 0,}]) def run_with_redis_lock(name): while True: if arrow.now().second % 5 == 0: # 二,獲取鎖 if rlock.acquire(): seckilling() # 釋放鎖 rlock.release() return
總結,咱們使用鎖的緣由,就是讓併發的程序造成阻塞,併發能夠引發的問題是數據不一致的狀況,使用鎖,造成阻塞,排隊使用數據,就不會形成數據不一致的問題了,固然了,阻塞確定會下降效率了,速度要慢不少。app