利用redis的乐观锁,实现秒杀系统的数据同步(基于watch实现)
import redis
conn = redis.Redis(host='127.0.0.1',port=6379)
# conn.set('count',1000)
with conn.pipeline() as pipe:
# 先监视,自己的值没有被修改过
conn.watch('count')
# 事务开始
pipe.multi()
old_count = conn.get('count')
count = int(old_count)
# input('我考虑一下')
if count > 0: # 有库存
pipe.set('count', count - 1)
# 执行,把所有命令一次性推送过去
ret2 = pipe.execute()
print(ret2) # [True]
ret = pipe.execute()
print(type(ret))
print(ret) # []
注:windows下如果数据被修改了,不会抛异常,只是返回结果的列表为空,mac和linux会直接抛异常
秒杀系统核心逻辑测试,创建100个线程并发秒杀
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import redis
from threading import Thread
import random, time
from redis import WatchError
stack_count = 100
def choose(name, conn):
# conn.set('count',10)
with conn.pipeline() as pipe:
# 先监视,自己的值没有被修改过
# while stack_count > 0:
try:
pipe.watch('count')
# 事务开始
pipe.multi()
old_count = conn.get('count')
count = int(old_count)
# input('我考虑一下')
# time.sleep(random.randint(1, 2))
# time.sleep(random.random())
if count > 0: # 有库存
# set之后对应ret 为[True]或者[], 而decr对应自减, 其ret 为[对应的count残余值]
pipe.set('count', count - 1)
# pipe.decr("count")
# 执行,把所有命令一次性推送过去
ret = pipe.execute()
print(ret)
if len(ret) > 0:
# print('第%s个人抢购成功' % name)
print("什么鬼")
else:
print('第%s个人抢购失败' % name)
except WatchError as e:
# 打印WatchError异常, 观察被watch锁住的情况
print(e)
print("当前用户抢购失败")
pipe.unwatch()
return
if __name__ == '__main__':
conn = redis.Redis(host='127.0.0.1', port=6379)
for i in range(2000):
t = Thread(target=choose, args=(i, conn))
t.start()
上面列子个人网上找来参考该动挺多, 实现了对规定秒杀库存数的完整性
个人代码的实现逻辑>>>:
实现了货物存在时部分用户可购买商品成功, 部分用户因为线程操作问题, 不能购买到货物, 在except部分进行了对应的逻辑打印, 而在 货物处于0 时候则报出 当前第几用户购买失败的效果, 实现了个人觉得测试下没有问题的秒杀
理解后, 部分复制之
参考文献地址>>>:
https://www.cnblogs.com/wangwei916797941/p/10030882.html
https://www.cnblogs.com/liuqingzheng/p/9997092.html
原文:https://www.cnblogs.com/suren-apan/p/11964454.html