性能工具之 Locust 简单入门

简介: 【4月更文挑战第1天】Locust是一个易于使用,分布式,用户负载测试工具。它用于负载测试web站点(或其他系统)并计算一个系统可以处理多少并发用户。

前言

Locust is an easy-to-use, distributed, user load testing tool. It is intended for load-testing web sites (or other systems) and figuring out how many concurrent users a system can handle.

Locust是一个易于使用,分布式,用户负载测试工具。它用于负载测试web站点(或其他系统)并计算一个系统可以处理多少并发用户。

The idea is that during a test, a swarm of locusts will attack your website. The behavior of each locust (or test user if you will) is defined by you and the swarming process is monitored from a web UI in real-time. This will help you battle test and identify bottlenecks in your code before letting real users in.

在测试中,一群蝗虫会攻击你的网站。每个蝗虫(或者测试用户)的行为由您定义,集群过程由web UI实时监控。这将帮助您在让真正的用户进入之前进行测试并识别代码中的瓶颈。

Locust is completely event-based, and therefore it’s possible to support thousands of concurrent users on a single machine. In contrast to many other event-based apps it doesn’t use callbacks. Instead it uses light-weight processes, through gevent. Each locust swarming your site is actually running inside its own process (or greenlet, to be correct). This allows you to write very expressive scenarios in Python without complicating your code with callbacks.

Locust完全是基于事件的,因此在一台机器上支持数千个并发用户是可能的。与许多其他基于事件的应用程序不同,它不使用回调。相反,它通过gevent使用轻量级进程。每个聚集在你的站点上的蝗虫实际上是在它自己的进程中运行的(或者说是greenlet)。这允许您用Python编写非常有表现力的场景,而不用回调使代码复杂化。

帮助文档:https://docs.locust.io/en/stable/what-is-locust.html

快速安装

pip install locustio

主要命令

locust --help

Usage: locust [options] [LocustClass [LocustClass2 ... ]]

Options:
  -h, --help            show this help message and exit
  -H HOST, --host=HOST  Host to load test in the following format:
                        http://10.21.32.33
  --web-host=WEB_HOST   Host to bind the web interface to. Defaults to '' (all
                        interfaces)
  -P PORT, --port=PORT, --web-port=PORT
                        Port on which to run web host
  -f LOCUSTFILE, --locustfile=LOCUSTFILE
                        Python module file to import, e.g. '../other.py'.
                        Default: locustfile
  --csv=CSVFILEBASE, --csv-base-name=CSVFILEBASE
                        Store current request stats to files in CSV format.
  --master              Set locust to run in distributed mode with this
                        process as master
  --slave               Set locust to run in distributed mode with this
                        process as slave
  --master-host=MASTER_HOST
                        Host or IP address of locust master for distributed
                        load testing. Only used when running with --slave.
                        Defaults to 127.0.0.1.
  --master-port=MASTER_PORT
                        The port to connect to that is used by the locust
                        master for distributed load testing. Only used when
                        running with --slave. Defaults to 5557. Note that
                        slaves will also connect to the master node on this
                        port + 1.
  --master-bind-host=MASTER_BIND_HOST
                        Interfaces (hostname, ip) that locust master should
                        bind to. Only used when running with --master.
                        Defaults to * (all available interfaces).
  --master-bind-port=MASTER_BIND_PORT
                        Port that locust master should bind to. Only used when
                        running with --master. Defaults to 5557. Note that
                        Locust will also use this port + 1, so by default the
                        master node will bind to 5557 and 5558.
  --expect-slaves=EXPECT_SLAVES
                        How many slaves master should expect to connect before
                        starting the test (only when --no-web used).
  --no-web              Disable the web interface, and instead start running
                        the test immediately. Requires -c and -r to be
                        specified.
  -c NUM_CLIENTS, --clients=NUM_CLIENTS
                        Number of concurrent Locust users. Only used together
                        with --no-web
  -r HATCH_RATE, --hatch-rate=HATCH_RATE
                        The rate per second in which clients are spawned. Only
                        used together with --no-web
  -t RUN_TIME, --run-time=RUN_TIME
                        Stop after the specified amount of time, e.g. (300s,
                        20m, 3h, 1h30m, etc.). Only used together with --no-
                        web
  -L LOGLEVEL, --loglevel=LOGLEVEL
                        Choose between DEBUG/INFO/WARNING/ERROR/CRITICAL.
                        Default is INFO.
  --logfile=LOGFILE     Path to log file. If not set, log will go to
                        stdout/stderr
  --print-stats         Print stats in the console
  --only-summary        Only print the summary stats
  --no-reset-stats      [DEPRECATED] Do not reset statistics once hatching has
                        been completed. This is now the default behavior. See
                        --reset-stats to disable
  --reset-stats         Reset statistics once hatching has been completed.
                        Should be set on both master and slaves when running
                        in distributed mode
  -l, --list            Show list of possible locust classes and exit
  --show-task-ratio     print table of the locust classes' task execution
                        ratio
  --show-task-ratio-json
                        print json data of the locust classes' task execution
                        ratio
  -V, --version         show program's version number and exit

快速上手

第一步,编写一盒简单的脚本。

# -*- coding: utf-8 -*-
# @Time    : 2019/12/31 20:24
# @Author  : 7DGroup
# @File    : SevenLoust.py
# coding:utf-8

from locust import HttpLocust, TaskSet, task

# HttpLocust 这个类的作用是用来发送http请求的
# TaskSet   这个类是定义用户行为的,相当于loadrunnerhttp协议的脚本,jmeter里面的http请求一样,要去干嘛的
# task   这个task是一个装饰器,它用来把一个函数,装饰成一个任务,也可以指定他们的先后执行顺序

class SevenLoust(TaskSet):
    # 自己定义的类,继承TaskSet,也就是这个类是实现咱们要去请求什么的
    '''打开7DGroup'''

    @task(1)  # @task#用task装饰器把这个函数装饰成一个咱们要执行的性能任务
    def open_7dtest(self):  # 这个函数里面定义的是咱们要具体做的操作
        # 定义requests的请求头
        header = {
   
   
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"}

        r = self.client.get("/", headers=header, verify=False)  # 请求这个url里面的哪个路径,
        print(r.status_code)
        assert r.status_code == 200


class websitUser(HttpLocust):
    # 这个类继承了HttpLocust,代表每个并发里面的每个用户
    task_set = SevenLoust  # 这个是每个用户都去干什么,指定了 SevenLoust 这个类,
    min_wait = 3000  # 单位毫秒
    max_wait = 6000  # 单位毫秒


if __name__ == "__main__":
    import os

    # -f是指定一个python文件 后面跟上咱们刚才写的python文件
    # --host是你要访问哪个网站,后面跟网站的url
    os.system("locust -f sevenLoust.py --host=http://www.7dtest.com/7DGroup/")

点击启动
image.png
image.png

打开浏览器显示:
image.png

参数说明:

  • Number of users to simulate 设置虚拟用户总数
  • Hatch rate (users spawned/second) 每秒启动虚拟用户数

第二步,点击 Start swarming开始运行性能测试。

image.png

主要参数说明:

  • Type:请求类型;
  • Name:请求路径;
  • requests:当前请求的数量;
  • fails:当前请求失败的数量;
  • Median:中间值,单位毫秒,一般服务器响应时间低于该值,而另一半高于该值;
  • Average:所有请求的平均响应时间,毫秒;
  • Min:请求的最小的服务器响应时间,毫秒;
  • Max:请求的最大服务器响应时间,毫秒;
  • Content Size:单个请求的大小,单位字节;
  • reqs/sec:每秒钟请求的个数。

第三步,查看报告显示。

吞吐量/每秒响应事务数(rps)实时统计
image.png

平均响应时间/平均事务数实时统计
image.png

虚拟用户数运行
image.png

第四步,停止点击按钮结束测试
image.png

总结

以上是简单上手示例,只要会点 Python 基础,就可以快速入门。

目录
相关文章
|
SQL 数据库 开发者
PyCharm社区版够用吗
PyCharm社区版够用吗
2950 0
|
关系型数据库 MySQL Java
【JMeter】(3)---MySQL压测
【JMeter】(3)---MySQL压测
745 0
|
存储 JavaScript 前端开发
细读 Git | 让你弄懂 origin、HEAD、FETCH_HEAD 相关内容
细读 Git | 让你弄懂 origin、HEAD、FETCH_HEAD 相关内容
6416 2
细读 Git | 让你弄懂 origin、HEAD、FETCH_HEAD 相关内容
|
6月前
|
存储 测试技术 数据库
Agent Memory主流产品横评与选型指南
本文横评10大Agent记忆方案,直击RAG与向量库的局限:缺乏时序追踪、一致性保障、分层管理与智能路由四大核心能力。从腾讯DB的高准确率、Zep的情节图谱、EverMemOS的多模态认知,到TiMem的五层时序树,全面解析各方案架构、性能与适用场景,助您科学选型。(239字)
|
8月前
|
消息中间件 Oracle Java
Java EE已死?变成Jakarta EE了?一篇文讲清楚
你是否被Java SE、EE、ME和Jakarta EE绕晕?本文用“商业帝国”比喻厘清三者关系:SE是地基(必学核心),EE/Jakarta EE是大厦(企业级开发,现由Eclipse基金会维护),ME已成历史。Android用Java语法但非标准Java。
Java EE已死?变成Jakarta EE了?一篇文讲清楚
|
9月前
|
存储 缓存 NoSQL
吃透 Redis 核心原理:内存模型、数据结构与持久化,从根上解决 90% 线上问题
本文深入剖析Redis三大核心基石:内存模型(含内存划分、碎片优化、过期与淘汰策略)、底层数据结构(String/Hash/List/Set/ZSet及扩展结构)和持久化机制(RDB/AOF/混合持久化),助开发者从set/get表层用法进阶到根因级问题解决。
882 2
|
存储 算法 关系型数据库
向量数据库深度剖析:核心优劣势 + 适用场景,避开 RAG 落地的选型坑
本文深度剖析向量数据库:揭示其在RAG系统中实现语义检索的核心价值与六大优势,直面模型依赖强、模糊匹配、硬件成本高、不支持事务等五大劣势,并给出精准选型指南与落地避坑策略,助你选对工具、用好RAG。
|
12月前
|
存储 机器学习/深度学习 人工智能
GEO 优化必备:RAG 技术全解析(基于知识密集型 NLP 经典论文)
2020 年论文提出的 RAG(检索增强生成),专治大模型 “幻觉、知识过时” 等落地痛点。它将 “检索外部知识” 与 “生成回答” 深度绑定,先精准抓取相关知识片段,再让模型基于证据生成内容。通过端到端联合训练,检索与生成协同优化,事实准确率显著提升,幻觉率大降。无需重训模型即可更新知识,还能追溯答案来源。如今成企业客服、医疗法律等领域刚需,推动大模型从 “通用” 走向 “可信实用”。这让我们做GEO优化就有了基础理论和方法。
GEO 优化必备:RAG 技术全解析(基于知识密集型 NLP 经典论文)
|
数据采集 人工智能 自然语言处理
Playwright MCP 浏览器自动化框架全面解析
Playwright MCP是微软推出的开源项目,结合Playwright与MCP协议,让AI通过结构化数据直接操作浏览器。告别传统视觉识别,实现高效、精准的网页自动化,广泛应用于测试、爬虫、办公自动化等场景,大幅提升效率与可靠性。
|
存储 算法 安全
G1原理—2.G1是如何提升分配对象效率
本文深入探讨了G1垃圾回收器中对象分配的原理与机制,包括TLAB(线程本地分配缓冲)的作用、快速分配与慢速分配的区别及流程。首先分析了G1的对象分配原理,强调了停顿预测模型和无锁化分配的重要性。接着详细解析了TLAB机制,涵盖其大小确定、满时处理以及如何借助指针碰撞法实现高效分配。同时讨论了大对象分配的特点及其与普通对象分配的不同之处。最后,针对慢速分配失败的情况,介绍了G1如何通过FGC(Full GC)进行最终尝试,确保系统在极端情况下的稳定运行。整体内容围绕提升分配效率与减少GC压力展开,为理解G1的工作机制提供了全面视角。
G1原理—2.G1是如何提升分配对象效率

热门文章

最新文章