locust快速入门--使用分布式提高测试压力

背景:

使用默认的locust启动命令进行压测时,尽管已经将用户数设置大比较大(400),但是压测的时候RPS一直在100左右。需要增加压测的压力。

问题原因:

如果你是通过命令行启动的或者参考之前文章的启动方式:

  • 命令行:

  • locust 库方法:
    `

因为create_local_runner会创建一个LocalRunner,这个runner只有一个WorkerNode

解决方式:

  • 单机:充分利用CPU每一个核心

    • os_start(True),指定参数True``则充分利用cpu的性能,否则就和之前调用create_local_runner一样。 使用os、multiprocessing完成, 模拟的是命令行启动locust的操作.。
    • local_start(True),使用locust的库方法,根据CPU的核心数、线程数创建WorkerNode
  • 多机:利用多台机器的能力提高测试压力

    • slave_start(master_ip, master_port=5557),指定主机的IP及端口号。
    python 复制代码
    # -*- coding:UTF-8 -*-
    
    """
     @ProjectName  : pyExamples 
     @FileName     : locust_demo
     @Description  : 
     @Time         : 2024/1/4 下午11:30
     @Author       : Qredsun
     """
    import os
    import socket
    import psutil
    from multiprocessing import Process
    from locust import HttpUser, events, task, between
    from locust.env import Environment
    
    
    class UserRun(HttpUser):
        wait_time = between(min_wait=0.1, max_wait=0.2)  # 设置task运行间隔
    
        @task  # 装饰器,说明下面是一个任务
        def getuser_(self):
            url = 'https://analytics.cnblogs.com/api/v1/reports'  # 接口请求的URL地址
            payload = {"blogId": 485117, "postId": 10365033,
                       "url": "https://www.cnblogs.com/happyyangyanghappy/p/10365033.html", "resolution": "1920x1080",
                       "referrer": "https://www.ecosia.org/", "createdAt": "2024-01-04T16:17:52.241Z"}
            with  self.client.post(url, json=payload, catch_response=True) as rsp:
                if rsp.status_code == 200:
                    rsp.success()
                else:
                    rsp.failure(f'接口调用失败:{rsp.json()}')
    
    
    def current_ip():
        ip = None
        interfaces = psutil.net_connections(kind='inet4')
        for interface in interfaces:
            if interface.type == socket.SocketKind.SOCK_STREAM and interface.status is not None and bool(interface.raddr):
                if interface.raddr.ip != "127.0.0.1":
                    print(interface.laddr.ip)
                    ip = interface.laddr.ip
                break
        return ip
    
    
    def local_start(multiprocess=False, master_ip=None):
        # 使用locust库启动
        web_host = current_ip()
        web_port = 8089
    
        runners = []
    
        master_env = Environment(user_classes=[UserRun], events=events)
        if multiprocess:
            # 主节点
            master_ip = web_host
            master_port = 5557
            master_runner = master_env.create_master_runner(master_bind_host=master_ip, master_bind_port=master_port)
            # 工作节点数量
            process_num = psutil.cpu_count()
    
            # slave
            for _ in range(process_num):
                env = Environment(user_classes=[UserRun], events=events)
                slave_runner = env.create_worker_runner(master_host=master_ip, master_port=master_port)
                runners.append(slave_runner)
    
        else:
            master_runner = master_env.create_local_runner()
        runners.append(master_runner)
        web_ui = master_env.create_web_ui(host=web_host, port=web_port)
        runners.append(web_ui)
    
        master_env.events.init.fire(environment=master_env, runner=master_runner, web_ui=web_ui)
    
        for runner in runners:
            runner.greenlet.join()
    
    
    def os_start(multiprocess=False):
        # 使用os库启动
        web_host = current_ip()
        web_port = 8089
    
        master_ip = web_host
        master_port = 5557
    
        master_cmd = f"locust -f {os.path.basename(__file__)}  --web-host {web_host} --web-port {web_port} --run-time 180s"
    
        process_num = psutil.cpu_count(logical=True)
        process_list = []
        if multiprocess:
            if os.name == "nt":
                # Windows 系统
                master_cmd += f" --master --master-bind-host {master_ip} --master-bind-port {master_port}"
                process_list.append(Process(target=os.system, args=(master_cmd,)))
                slave_cmd = f"locust -f {os.path.basename(__file__)}  --worker --master-host {master_ip} --master-port {master_port}"
                for _ in range(process_num):
                    process_list.append(Process(target=os.system, args=(slave_cmd,)))
            else:
                # linux
                master_cmd += f" --master-host {master_ip} --master-port {master_port} --processes -1"
                process_list.append(Process(target=os.system, args=(master_cmd,)))
        else:
            process_list.append(Process(target=os.system, args=(master_cmd,)))
    
        for p in process_list:
            p.start()
    
        for p in process_list:
            p.join()
    
    def slave_start(master_ip, master_port=5557):
        # 使用locust库启动
        runners = []
        # 工作节点数量
        process_num = psutil.cpu_count()
    
        # slave
        for _ in range(process_num):
            env = Environment(user_classes=[UserRun], events=events)
            slave_runner = env.create_worker_runner(master_host=master_ip, master_port=master_port)
            runners.append(slave_runner)
    
        for runner in runners:
            runner.greenlet.join()
    
    if __name__ == '__main__':
        # os_start(True)
        local_start(True)

工作效果:


相关推荐
大得36935 分钟前
django生成迁移文件,执行生成到数据库
后端·python·django
大志说编程42 分钟前
LangChain框架入门17: 手把手教你创建LLM工具
python·langchain·ai编程
jakeswang1 小时前
应用缓存不止是Redis!——亿级流量系统架构设计系列
redis·分布式·后端·缓存
R-G-B1 小时前
【P38 6】OpenCV Python——图片的运算(算术运算、逻辑运算)加法add、subtract减法、乘法multiply、除法divide
人工智能·python·opencv·图片的运算·图片加法add·图片subtract减法·图片乘法multiply
数据智能老司机1 小时前
MCP 实战——全局视角:为什么 MCP 将成为 AI 的颠覆者
python·llm·mcp
在星空下1 小时前
Fastapi-Vue3-Admin
前端·python·fastapi
cxyll12342 小时前
从接口自动化测试框架设计到开发(三)主流程封装、返回数据写入excel
前端·python·excel
Kyln.Wu2 小时前
【python实用小脚本-190】Python一键删除PDF任意页:输入页码秒出干净文件——再也不用在线裁剪排队
服务器·python·pdf
九章云极AladdinEdu2 小时前
Scikit-learn通关秘籍:从鸢尾花分类到房价预测
人工智能·python·机器学习·分类·scikit-learn·gpu算力
抠头专注python环境配置3 小时前
Pytorch GPU版本安装保姆级教程
pytorch·python·深度学习·conda