数据库
首页 > 数据库> > redis分布式锁

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 ...

  

标签:locked,contextmanager,lock,redis,expire,key,分布式
来源: https://www.cnblogs.com/wzy23/p/15438141.html