redis setNx原子锁


https://github.com/suqi/rlock/blob/master/rlock.py

保持逻辑并发情况不产生多次结果

常用于下单,钱包,抢购,秒杀等场景 

 1 LOCK_TIMEOUT = 3
 2 lock = 0
 3 lock_timeout = 0
 4 lock_key = 'lock.foo'
 5 
 6 # 获取锁
 7 while lock != 1:
 8     now = int(time.time())
 9     lock_timeout = now + LOCK_TIMEOUT + 1
10     lock = redis_client.setnx(lock_key, lock_timeout)
11     if lock == 1 or (now > int(redis_client.get(lock_key))) and now > int(redis_client.getset(lock_key, lock_timeout)):
12         break
13     else:
14         time.sleep(0.001)
15 
16 # 已获得锁
17 do_job()
18 
19 # 释放锁
20 now = int(time.time())
21 if now < lock_timeout:
22     redis_client.delete(lock_key)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM