4

使用ApacheBench来对美多商城的秒杀功能进行高并发压力测试

 2 years ago
source link: https://v3u.cn/a_id_65
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

使用ApacheBench来对美多商城的秒杀功能进行高并发压力测试

首页 - Python/2019-04-12

    秒杀功能众所周知,低廉的价格会引来很多用户趋之若鹜的争抢点击,导致一系列的服务器负载问题,服务器负载太大而影响程序效率也是很常见的,Apache服务器自带有一个叫AB(ApacheBench)的工具,可以对服务器进行负载测试

同时美多商城的秒杀功能也会被高负载影响,从而导致超卖现象

安装xampp软件

进入 c:/xampp/apache/bin

基本用法:

ab  -n 全部请求数 -c 并发数测试url

可以将ab.exe 加入系统环境变量;或直接切换置 ab 目录执行。如: C:WindowsSystem32> cd C:xamppapachebin

关于秒杀很好理解,就是每一个用户抢到商品之后,库存进行递减操作

#定义秒杀接口
def miaosha(request):
    res_one = News.objects.get(pk=1)
    if res_one.pd > 0:
        time.sleep(5)
        with connection.cursor() as c:
            c.execute(' update news set pd = pd - 1 where id = 1 ')
        return HttpResponse('ok')
    else:
        return HttpResponse('没有了')

索然逻辑上很严谨,代码也很简单,但是在高并发没有锁的情况下,数据库会过载导致超卖现象,也就是库存变为负数

于是就得引入redis来解决这一个问题:

r = redis.Redis(host='localhost', port=6379)


#定义过载限制
def limit_handler():
    """
    return True: 允许; False: 拒绝
    """
    amount_limit = 3  # 限制数量
    keyname = 'limit'  # 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)
        with connection.cursor() as c:
            c.execute(' update news set pd = pd - 1 where id = 1 ')
        return HttpResponse('ok')
    else:
        return HttpResponse('没有了')

这样只要配合这个方法,在进行修改mysql数据库的操作,就可以防止超限

</div


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK