天天看點

redis分布式鎖

from contextlib import contextmanager

@contextmanager
def lock(redis, lock_key, expire):
    try:
        locked = redis.set(lock_key, 'locked', expire)
        yield locked
    finally:
        redis.delete(lock_key)

# 業務調用 with 代碼塊執行結束後 自動釋放鎖資源
with lock(redis, 'locked', 3) as locked:
    if not locked:
        return
    # do something ...      

  

繼續閱讀