解决高并发的问题python_python ---解决高并发超卖问题
使用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('沒有了')
總結
以上是生活随笔為你收集整理的解决高并发的问题python_python ---解决高并发超卖问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python cnn_使用python中
- 下一篇: python生成柱状图 不显示_pyth