秒杀方法
def sell(product_id: str):
with r.pipeline() as pipe: # 初始化 pipe
while True:
try:
pipe.watch(product_id) # 监听库存
c = int(pipe.get(product_id)) # 查看当前库存
if c > 0: # 有库存则售卖
pipe.multi() # 开始事务
c -= 1
pipe.set(product_id, c) # 减少库存
pipe.execute() # 执行事务
return True
else:
return False
except Exception as e:
continue
finally:
# 重置 pipe,准备下次抢购
pipe.reset()
多线程工具
class BaseThread(Thread):
"""封装异步多线程工具"""
def __init__(self, func, *args, **kwargs):
super(BaseThread, self).__init__()
self.func = func
self._args = args
self._kwargs = kwargs
def run(self):
self.func(*self._args, **self._kwargs)