Locust使用手册--Locust配置

本文介绍Locust性能测试工具的配置方法,包括命令行参数、环境变量及配置文件等配置方式。涵盖如何设置并发用户数、生成速率、运行时间等关键参数,并解释了在无WebUI环境下运行及多Locustfile文件的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

配置

命令行参数

Locust主要通过命令行参数进行配置

$locust --help
Usage: locust [OPTIONS] [UserClass ...]

Common options:
  -h, --help            show this help message and exit
  -f LOCUSTFILE, --locustfile LOCUSTFILE
                        Python module to import, e.g. '../other_test.py'.
                        Either a .py file, multiple comma-separated .py files
                        or a package directory. Defaults to 'locustfile'.
  --config CONFIG       Config file path
  -H HOST, --host HOST  Host to load test in the following format:
                        http://10.21.32.33
  -u NUM_USERS, --users NUM_USERS
                        Peak number of concurrent Locust users. Primarily used
                        together with --headless or --autostart. Can be
                        changed during a test by keyboard inputs w, W (spawn
                        1, 10 users) and s, S (stop 1, 10 users)
  -r SPAWN_RATE, --spawn-rate SPAWN_RATE
                        Rate to spawn users at (users per second). Primarily
                        used together with --headless or --autostart
  -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
                        --headless or --autostart. Defaults to run forever.
  -l, --list            Show list of possible User classes and exit

Web UI options:
  --web-host WEB_HOST   Host to bind the web interface to. Defaults to '*'
                        (all interfaces)
  --web-port WEB_PORT, -P WEB_PORT
                        Port on which to run web host
  --headless            Disable the web interface, and start the test
                        immediately. Use -u and -t to control user count and
                        run time
  --autostart           Starts the test immediately (without disabling the web
                        UI). Use -u and -t to control user count and run time
  --autoquit AUTOQUIT   Quits Locust entirely, X seconds after the run is
                        finished. Only used together with --autostart. The
                        default is to keep Locust running until you shut it
                        down using CTRL+C
  --web-auth WEB_AUTH   Turn on Basic Auth for the web interface. Should be
                        supplied in the following format: username:password
  --tls-cert TLS_CERT   Optional path to TLS certificate to use to serve over
                        HTTPS
  --tls-key TLS_KEY     Optional path to TLS private key to use to serve over
                        HTTPS
  --class-picker        Enable select boxes in the web interface to choose
                        from all available User classes and Shape classes

Master options:
  Options for running a Locust Master node when running Locust distributed. A Master node need Worker nodes that connect to it before it can run load tests.

  --master              Set locust to run in distributed mode with this
                        process as master
  --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.
  --expect-workers EXPECT_WORKERS
                        How many workers master should expect to connect
                        before starting the test (only when
                        --headless/autostart is used).
  --expect-workers-max-wait EXPECT_WORKERS_MAX_WAIT
                        How long should the master wait for workers to connect
                        before giving up. Defaults to wait forever

Worker options:
  Options for running a Locust Worker node when running Locust distributed.
  Only the LOCUSTFILE (-f option) needs to be specified when starting a Worker, since other options such as -u, -r, -t are specified on the Master node.

  --worker              Set locust to run in distributed mode with this
                        process as worker
  --master-host MASTER_NODE_HOST
                        Host or IP address of locust master for distributed
                        load testing. Only used when running with --worker.
                        Defaults to 127.0.0.1.
  --master-port MASTER_NODE_PORT
                        The port to connect to that is used by the locust
                        master for distributed load testing. Only used when
                        running with --worker. Defaults to 5557.

Tag options:
  Locust tasks can be tagged using the @tag decorator. These options let specify which tasks to include or exclude during a test.

  -T [TAG [TAG ...]], --tags [TAG [TAG ...]]
                        List of tags to include in the test, so only tasks
                        with any matching tags will be executed
  -E [TAG [TAG ...]], --exclude-tags [TAG [TAG ...]]
                        List of tags to exclude from the test, so only tasks
                        with no matching tags will be executed

Request statistics options:
  --csv CSV_PREFIX      Store current request stats to files in CSV format.
                        Setting this option will generate three files:
                        [CSV_PREFIX]_stats.csv, [CSV_PREFIX]_stats_history.csv
                        and [CSV_PREFIX]_failures.csv
  --csv-full-history    Store each stats entry in CSV format to
                        _stats_history.csv file. You must also specify the '--
                        csv' argument to enable this.
  --print-stats         Print stats in the console
  --only-summary        Only print the summary stats
  --reset-stats         Reset statistics once spawning has been completed.
                        Should be set on both master and workers when running
                        in distributed mode
  --html HTML_FILE      Store HTML report to file path specified

Logging options:
  --skip-log-setup      Disable Locust's logging setup. Instead, the
                        configuration is provided by the Locust test or Python
                        defaults.
  --loglevel LOGLEVEL, -L LOGLEVEL
                        Choose between DEBUG/INFO/WARNING/ERROR/CRITICAL.
                        Default is INFO.
  --logfile LOGFILE     Path to log file. If not set, log will go to stderr

Other options:
  --show-task-ratio     Print table of the User classes' task execution ratio.
                        Use this with non-zero --user option if some classes
                        define non-zero fixed_count attribute.
  --show-task-ratio-json
                        Print json data of the User classes' task execution
                        ratio. Use this with non-zero --user option if some
                        classes define non-zero fixed_count attribute.
  --version, -V         Show program's version number and exit
  --exit-code-on-error EXIT_CODE_ON_ERROR
                        Sets the process exit code to use when a test result
                        contain any failure or error
  -s STOP_TIMEOUT, --stop-timeout STOP_TIMEOUT
                        Number of seconds to wait for a simulated user to
                        complete any executing task before exiting. Default is
                        to terminate immediately. This parameter only needs to
                        be specified for the master process when running
                        Locust distributed.
  --equal-weights       Use equally distributed task weights, overriding the
                        weights specified in the locustfile.
  --enable-rebalancing  Allow to automatically rebalance users if new workers
                        are added or removed during a test run.

User classes:
  UserClass             Optionally specify which User classes that should be
                        used (available User classes can be listed with -l or
                        --list)

环境变量

也可以通过环境变量来设置选项。他们和命令行参数相同,但需要用大写且以LOCUST_为前缀。
在Linux/macOS系统:

$LOCUST_LOCUSTFILE=custom_locustfile.py locust

在Windows系统:

> set LOCUST_LOCUSTFILE=custom_locustfile.py
> locust

配置文件

也可以按照配置文件中的配置文件格式来设置选项。
Locust会在默认情况下查找~/.locust.conf./locust.conf,你可以使用--config标志来指定一个额外的文件。
例如:

# 当前目录下的master.conf
locustfile = locust_files/my_locust_file.py
headless = true
master = true
expect-workers = 5
host = http://target-system
users = 100
spawn-rate = 10
run-time = 10m
$locust --config=master.conf

批注
按以下的顺序读取(覆盖)配置值:
~/locust.conf -> ./locust.conf -> (file specified using --conf) -> env vars -> cmd args

所有可用的配置选项

下表记录了所有可用配置选项以及它们对应的环境和配置文件键值信息:

命令行环境配置文件描述
-f,--locustfileLOCUST_LOCUSTFILElocustfile导入python模块,例如:‘../other_test.py’。一个.py文件、多个逗号分隔的.py文件或包目录。默认是’locustfile
-H,--hostLOCUST_HOSThost加载测试时的主机格式为: http://10.21.32.33
-u,--usersLOCUST_USERSusersLocust高峰并发用户数。主要和-headless-autostart一起使用。在测试过程中可以通过键盘w,W(生成1,10个用户)和s,S(停止1,10个用户)进行修改用户数
-r,--spawn-rateLOCUST_SPAWN_RATEspawn-rate以(每秒用户数)生成用户的速率。主要和-headless-autostart一起使用
-t,--run-timeLOCUST_RUN_TIMErun-time在指定的时间值后停止运行。例如(300s,20m,3h,1h30m等)。只能和-headless-autostart一起使用。默认是一直运行
--web-hostLOCUST_WEB_HOSTweb-host绑定web界面的主机。默认为’*'(所有接口)
--web-port,-PLOCUST_WEB_PORTweb-port指定运行web主机的端口
--headlessLOCUST_HEADLESSheadless禁用web界面,立即启动测试。使用-u-t来控制用户数和运行时间
--autostartLOCUST_AUTOSTARTautostart立即启动测试(和--headless一样,但不禁用web UI界面)
--autoquitLOCUST_AUTOQUITautoquit在运行结束后X秒,完全退出Locust。只能和-autostart一起使用。默认是保持Locust运行直至按下CTRL+C才退出
--web-authLOCUST_WEB_AUTHweb-auth启用web界面的基本身份验证。应按以下格式提供:用户名:密码
--tls-certLOCUST_TLS_CERTtls-cert用于HTTPS提供服务的TLS证书的可选路径
--tls-keyLOCUST_TLS_KEYtls-key用于HTTPS提供服务的TLS私钥的可选路径
--class-pickerLOCUST_USERCLASS_PICKERclass-picker启用web界面中的选择框,从所有可用的用户类和形态类中进行选择
--masterLOCUST_MODE_MASTERmaster将locust设置为以分布式模式运行,并将此进程作为master(主服务器)
--master-bind-hostLOCUST_MASTER_BIND_HOSTmaster-bind-hostlocust master(主服务器)绑定的接口(主机名,ip)。仅在使用-master运行时使用。默认为*(所有可用的接口)
--master-bind-portLOCUST_MASTER_BIND_PORTmaster-bind-portlocust master(主服务器)绑定的端口,仅在使用-master运行时使用。默认是5557
--expect-workersLOCUST_EXPECT_WORKERSexpect-workers在开始测试之前需要连接多少worker主机(辅助服务器)(仅当-headless/autostart被使用时)
--expect-workers-max-waitLOCUST_EXPECT_WORKERS_MAX_WAITexpect-workers-max-wait主进程在等待worker(辅助服务器)主机连接多久后才可放弃。默认是一直等待
--workerLOCUST_MODE_WORKERworker将locust设置为以分布式模式运行,并将此进程设置为worker(辅助服务器)
--master-hostLOCUST_MASTER_NODE_HOSTmaster-host用于分布式负载测试的locust master(主服务器)的主机或IP地址。仅在使用-worker运行时使用。默认为127.0.0.1
--master-portLOCUST_MASTER_NODE_PORTmaster-port在分布式测试时locust主服务器的连接端口,仅在使用-worker运行时使用。默认是5557
-T,--tagsLOCUST_TAGStags从测试用例中得到包含标记的列表,以便只执行具有任何匹配标记的任务
-E,--exclude-tagsLOCUST_EXCLUDE_TAGSexclude-tags从测试用例中排除标记的列表,因此只执行不匹配标记的任务
--csvLOCUST_CSVcsv将当前请求统计数据以CSV格式存储到文件中。设置这个参数将会得到三个文件:[CSV_PREFIX]_stats.csv,[CSV_PREFIX]_stats_history.csv[CSV_PREFIX]_failures.csv
--csv-full-historyLOCUST_CSV_FULL_HISTORYcsv-full-history将每个统计的条目以CSV格式存储到_stats_history.csv文件中。必须指定-csv参数来启用此功能
--print-statsLOCUST_PRINT_STATSprint-stats在UI运行中启用定期打印请求统计信息
--only-summaryLOCUST_ONLY_SUMMARYonly-summary禁用在-headless运行期间定期打印请求统计信息
--reset-statsLOCUST_RESET_STATSreset-stats生成完成后重置统计数据。在分布式模式下运行时,应该在master(主服务器)和worker(辅助服务器)上同时设置
--htmlLOCUST_HTMLhtml将HTML报告存储到指定的文件路径
--skip-log-setupLOCUST_SKIP_LOG_SETUPskip-log-setup禁用Locust的日志记录设置。相反,配置是由Locust测试或Python默认值提供的
--loglevel,-LLOCUST_LOGLEVELloglevelDEBUG/INFO/WARNING/ERROR/CRITICAL中选择,默认是INFO级别
--logfileLOCUST_LOGFILElogfile指定日志文件的路径。如果未设置,log将转到stderr
--exit-code-on-errorLOCUST_EXIT_CODE_ON_ERRORexit-code-on-error设置当测试结果包含任何失败或错误时使用的程序退出代码
-s,--stop-timeoutLOCUST_STOP_TIMEOUTstop-timeout模拟用户在退出前完成任何执行任务所需要等待的秒数。默认值是立即终止。该参数只需要在运行Locust分布式时为主进程指定。

在没有web UI的情况下运行

参考在没有web UI的情况下运行

同时使用多个Locustfile

-f/--locustfile指令接收一个locustfile目录作为选项。Locust将递归搜索目录中所有的.py文件忽略locust.py_开头的文件。
例如:
使用以下文件结构:

├── locustfiles/
│   ├── locustfile1.py
│   ├── locustfile2.py
│   └── more_files/
│       ├── locustfile3.py
│       ├── locust.py
│       ├── _ignoreme.py
$locust -f locustfiles

Locust将会使用到locustfile1.py,locustfile2.py,more_files/locustfile3.py
此外,-f/--locustfile接受多个以逗号隔开的locustfiles。
例如:

$locust -f locustfiles/locustfile1.py,locustfiles/locustfile2.py,locustfiles/more_files/locustfile3.py

Locust将会使用到locustfile1.py,locustfile2.py,more_files/locustfile3.py

使用用户类UI选择器运行Locust

当通过--class-picker参数来运行Locust时,在Web UI界面上可以选择你想执行测试的形态类和用户类。没有选择则执行所有的用户类。
例如:
使用以下文件结构:

├── src/
│   ├── some_file.py
├── locustfiles/
│   ├── locustfile1.py
│   ├── locustfile2.py
│   └── more_files/
│       ├── locustfile3.py
│       ├── locust.py
│       ├── _ignoreme.py
│   └── shape_classes/
│       ├── DoubleWaveShape.py
│       ├── StagesShape.py
$locust -f locustfiles --class-picker

Web UI界面将显示:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uwsCBlIT-1671073326649)(image/userclass_picker_example.png)]

自定义参数

参考自定义参数章节

自定义统计设置

Locust统计信息的默认配置设置在stats.py文件的常量中。可以通过重置这些常量值来达到特定场景的需求。为此需要导入locust.stats模块以及重置常量的设置:

import locust.stats
locust.stats.CONSOLE_STATS_INTERVAL_SEC = 15

它可以直接在locust文件中使用或提取到单独的文件供所有的locust文件来调用。
可修改的统计参数列表如下:

参数名称用途描述
STATS_NAME_WIDTH控制台输出内容中请求名称的列宽度
STATS_TYPE_WIDTH控制台输出内容中请求类型的列宽度
CSV_STATS_INTERVAL_SEC设置此选项,实现CSV文件写入的时间间隔
CONSOLE_STATS_INTERVAL_SEC测试结果写入控制台的时间间隔
CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW计算当前响应时间百分比时,指定窗口大小/分辨率(以秒为单位)
PERCENTILES_TO_REPORT给要计算和报告的响应时间百分比列表
<think>嗯,用户现在提到他们目前仅支持仿真环境,接下来该怎么做。我需要先理解用户所处的阶段。之前已经给了他们关于从基础设施到内部验证和生产推广的详细方案,但用户现在可能处于更早期的阶段,即只有仿真环境,还没进入生产环境的混沌演练。 首先,用户可能是在搭建混沌演练平台的初期,可能已经完成了仿真环境的基础设施搭建,但还没有开始在生产环境实施。他们的问题可能是想知道如何从仿真环境过渡到更实际的应用阶段,或者如何验证他们的仿真环境是否足够可靠,以便后续推广。 接下来,我需要回顾之前的对话历史。用户之前询问的是完成基础设施后的步骤,现在的情况是仅支持仿真环境,所以可能需要更基础的步骤,比如如何优化仿真环境,建立流程,或者开始小范围的内部验证。 可能的用户需求包括: 1. 如何从仿真环境过渡到真实环境? 2. 在仅有仿真环境的情况下,如何有效测试和验证演练方案? 3. 如何为后续的生产环境推广做准备? 4. 如何确保团队在仿真环境中获得足够的经验和信心? 用户可能没有明确说明他们的具体业务场景,但根据之前的回复,可能涉及分布式系统、云原生架构等。用户可能属于技术团队,负责系统稳定性或DevOps,需要确保混沌演练能有效提升系统韧性。 需要确保回答覆盖以下几个方面: - 验证仿真环境的有效性 - 逐步引入更复杂的场景 - 建立流程和团队协作机制 - 准备向生产环境过渡的条件 可能还需要考虑用户可能面临的挑战,比如团队对混沌工程的理解不足,仿真环境与生产环境的差异,或者缺乏足够的监控和应急流程。因此,回答中需要包含具体的步骤、工具建议、流程建设以及风险控制措施。 最后,确保回答结构清晰,分阶段指导用户如何从当前阶段逐步推进,同时强调注意事项和关键成功因素,比如文化转变、逐步验证和监控的重要性。</think>以下是针对当前仅支持仿真环境的混沌演练平台,如何逐步推进落地的详细实施路径和关键策略: --- # **仿真环境混沌演练进阶实施计划** ## **1. 仿真环境深度验证(1-2个月)** ### **1.1 环境保真度校准** - **拓扑结构校验** ```python # 对比仿真环境与生产环境的服务依赖差异 def validate_topology(): sim_services = get_simulation_services() prod_services = get_production_services() missing_nodes = prod_services - sim_services assert len(missing_nodes) == 0, f"缺失关键节点: {missing_nodes}" ``` - **核心指标**:服务依赖匹配度需达95%以上,流量模型误差率<5% - **数据真实性增强** - 使用生产流量录制回放工具(如GoReplay)注入真实请求模式 - 构建影子数据库(Shadow DB),同步生产数据Schema与索引结构 ### **1.2 基础能力验证矩阵** | 测试维度 | 验证方法 | 验收标准 | |----------------|-----------------------------------|------------------------------| | 故障注入精度 | 对比预设参数与实际生效值 | 误差率<3%(如CPU占用±2%) | | 监控覆盖度 | 人工屏蔽监控探针后执行演练 | 关键指标缺失告警应在20秒内触发 | | 恢复有效性 | 强制中断恢复流程 | 系统应在预设超时阈值内自动触发备用方案 | --- ## **2. 演练场景分层推进策略** ### **2.1 场景复杂度分级** ```mermaid graph TD A[单组件故障] --> B[依赖链路中断] B --> C[资源竞争场景] C --> D[复合型灾难] D --> E[突增流量+硬件故障] ``` ### **2.2 典型场景实施示例 #### **2.2.1 L1级(单服务故障)** - **实施步骤**: 1. 在商品服务实例注入300ms延迟 2. 观察购物车服务超时熔断机制 3. 验证降级策略是否展示默认库存 - **监控重点**: - Hystrix线程池拒绝次数 - Redis缓存命中率波动 #### **2.2.2 L2级(跨系统影响)** - **模拟支付成功但订单未生成**: ```bash # 使用混沌工具拦截MQ消息 chaos-cli kafka --action delay --topic payment_callback \ --delay 10m --percentage 30 ``` - **预期结果**: - 对账系统应在15分钟内触发异常检测 - 补偿任务自动重试次数≥3次 --- ## **3. 向生产过渡的预备工作** ### **3.1 环境差异补偿机制** | 差异类型 | 缓解方案 | 工具推荐 | |----------------|-----------------------------------|-----------------------| | 硬件配置差异 | 在仿真环境叠加资源限制 | Docker --cpuset参数 | | 流量压力差异 | 使用Locust按生产QPS的120%施压 | Locust分布式压测集群 | | 数据规模差异 | 注入生产级别的测试数据(脱敏后) | JMeter CSV数据驱动 | ### **3.2 生产推演沙盘机制** - **演练模式**: - **只读模式**:在真实环境执行故障注入,但仅观察不实际影响业务 ```sql /* 模拟数据库慢查询但不修改数据 */ SET GLOBAL max_statement_time=0.1; SELECT /*+ MAX_EXECUTION_TIME(100) */ * FROM orders; ``` - **影子执行**:将故障影响限定在特定测试账号(如用户ID以_chaos结尾) --- ## **4. 关键支撑体系搭建** ### **4.1 自动化验证流水线 ```mermaid graph LR A[场景配置] --> B[环境预检] B --> C[故障注入] C --> D[指标采集] D --> E[自动断言] E --> F[生成验证报告] F --> G[环境清理] ``` ### **4.2 人员能力培养计划 - **角色专项训练**: | 角色 | 训练内容 | 考核方式 | |----------------|-----------------------------------|-----------------------| | 研发工程师 | 故障注入API调用与结果分析 | 完成3个场景演练报告 | | 运维工程师 | 熔断策略配置与应急手册执行 | 模拟故障恢复实操考核 | | 架构师 | 设计复合故障场景与架构弱点识别 | 输出系统脆弱性分析报告| --- ## **5. 风险控制升级** ### **5.1 仿真环境隔离方案 - **网络层**:使用Calico网络策略限制混沌实验传播范围 ```yaml apiVersion: projectcalico.org/v3 kind: NetworkPolicy metadata: name: chaos-isolation spec: selector: environment == 'simulation' ingress: - action: Deny source: selector: environment != 'simulation' egress: - action: Allow ``` ### **5.2 熔断逃生设计 - **三级熔断机制**: 1. **自动熔断**:API错误率>40%持续1分钟 2. **人工确认**:关键服务故障自动暂停等待审批 3. **强制终止**:实验超时未结束则触发全局回滚 --- **下一步行动建议**: 1. 建立「场景-环境-指标」三维验证矩阵,每完成20个仿真演练即进行阶段性评审 2. 在仿真环境构建「灾难走廊」:连续触发5个关联故障,测试系统极限承压能力 3. 开始筹备生产环境演练的「白名单」机制,与业务方确定可演练时段与范围
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值