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)