pip:https://pypi.org/project/python-redis-lock/
1. 安装 python-redis-lock
pip install python-redis-lock
2. 使用 redis 锁
from redis import Redis
conn = Redis()
import redis_lock
lock = redis_lock.Lock(conn, "name-of-the-lock")
if lock.acquire(blocking=False):
print("Got the lock.")
lock.release()
else:
print("Someone else has the lock.")
或者使用 with
conn = StrictRedis()
with redis_lock.Lock(conn, "name-of-the-lock"):
print("Got the lock. Doing some work ...")
time.sleep(5)