import redis
def add_to_cart(redis_client, product_id, cart_key, stock_key, increment_amount):
pipe = redis_client.pipeline()
try:
# 开启事务
pipe.watch(stock_key)
# 获取库存数量
stock = int(pipe.get(stock_key))
# 获取购物车中该商品数量
cart_count = pipe.hget(cart_key, product_id)
if cart_count is None:
cart_count = 0
else:
cart_count = int(cart_count)
if cart_count + increment_amount <= stock:
pipe.multi()
# 增加购物车中商品数量
pipe.hincrby(cart_key, product_id, increment_amount)
# 减少库存数量
pipe.decrby(stock_key, increment_amount)
pipe.execute()
else:
raise Exception("库存不足")
except Exception as e:
print(f"发生异常: {e}")
pipe.unwatch()
finally:
pipe.reset()
if __name__ == "__main__":
r = redis.Redis(host='localhost', port=6379, db=0)
# 初始化库存
r.set('stock_key', 100)
# 初始化购物车
r.hset('cart_key', 'product_1', 0)
add_to_cart(r, 'product_1', 'cart_key','stock_key', 5)