使用redis 解决美多商城超卖的问题
import redis
r = redis.Redis(host='localhost', port=6379)
#定义过载
def limit_handler():
"""
return True: 允许; False: 拒绝
"""
amount_limit = 3 # 限制数量
keyname = 'limit123' # redis key name
incr_amount = 1 # 每次增加数量
# 判断key是否存在
if not r.exists(keyname):
# 为了方便测试,这里设置默认初始值为95
# setnx可以防止并发时多次设置key
r.setnx(keyname, 0)
# 数据插入后再判断是否大于限制数
if r.incrby(keyname, incr_amount) <= amount_limit:
return True
return False
#定义秒杀接口
def miaosha(request):
res_one = News.objects.get(pk=1)
if limit_handler():
#if res_one.pd > 0:
time.sleep(5)
# res_one.pd = res_one.pd - 1
# res_one.save()
with connection.cursor() as c:
c.execute(' update news set pd = pd - 1 where id = 1 ')
return HttpResponse('ok')
else:
return HttpResponse('没有了')