使用改装器的函数在多容器同时运行时,不会同时执行装饰器内的函数,避免多容器并行带来的问题。
def thing_lock(cls, name, expiration_time=2, time_out=3):
"""
代码悲观锁
功能:避免函数同时执行,产生不可预知的问题
"""
def outer_func(func):
def wrapper_func(*args, **kwargs):
lock_name = f'lock:{name}'
end_time = time.time() + time_out
while time.time() < end_time:
if _redis_client.setnx(lock_name, expiration_time):
_redis_client.expire(lock_name, expiration_time)
data = func(*args, **kwargs)
_redis_client.delete(lock_name)
return data
time.sleep(0.001)
return func(*args, **kwargs)
return wrapper_func
return outer_func
需要根据自身代码,调整redis连接部分