Locust 安装指南

Locust 安装指南:Ubuntu 22.04 用 pip3 安装 Python 生态并发压测工具 Locust,依赖、版本验证、headless 压测验证、卸载与参考链接,均已实测通过

性能测试与压测Locust2026/10/09

Locust 安装指南

目标:在 Ubuntu 22.04 从零安装基于 Python 的并发压测工具 Locust,实测验证 locust --version 与一次 20 秒 headless 压测均通过。

环境信息:操作系统 Ubuntu 22.04(x86_64);Python 3.10.12;通过 pip3 安装 Locust 2.46.0;实测压测目标为内网 Nginx 8(监听 80)。

前置条件:以 root 执行安装命令;先安装 python3 与 python3-pip;Ubuntu 22.04 需可访问 PyPI(或配置国内镜像源);本机与目标 Nginx 8 需内网直连。

💡 说明:Locust 是纯 Python 的负载测试工具,采用协程(gevent)模拟高并发用户。它用 Python 脚本(locustfile)定义用户行为,既支持命令行 headless 压测,也自带 Web 仪表盘。相比 ab/wrk,Locust 更侧重「模拟真实用户行为」与「分布式(多机 master/worker)压测」。

一、Ubuntu 22.04 安装

1.1 安装 Python 与 pip

apt-get update
apt-get install -y python3 python3-pip

验证版本:

python3 --version
pip3 --version

实测回显:

Python 3.10.12
pip 22.0.2 from /usr/lib/python3/dist-packages/pip (python 3.10)

1.2 用 pip3 安装 Locust

建议配置国内 PyPI 镜像以加速下载:

pip3 install --disable-pip-version-check -i https://pypi.tuna.tsinghua.edu.cn/simple locust

实测回显(关键尾部):

Successfully installed ... locust-2.46.0 ...

验证版本:

locust --version

实测回显:

locust 2.46.0 from /usr/local/lib/python3.10/dist-packages/locust (Python 3.10.12)

⚠️ 注意:实测 locust --version 尾部会附带 gevent 清理阶段的 RuntimeError: greenlet is being finalized 异常输出。这是 gevent 在进程退出时释放资源的已知现象,不影响功能与版本信息定位,可忽略。

二、运行验证(headless 压测)

编写最小 locustfile 并做一次 20 秒压测,验证工具与网络链路:

cat > /opt/locustfile.py <<'EOF'
from locust import HttpUser, task, between

class NginxUser(HttpUser):
    wait_time = between(0.1, 0.5)

    @task
    def get_root(self):
        self.client.get("/")
EOF
locust -f /opt/locustfile.py --headless -u 5 -r 1 -t 20s --host http://192.168.10.10/

实测回显(关键部分):

Run time limit set to 20 seconds
Ramping to 5 users at a rate of 1.00 per second
...
All users spawned: {"NginxUser": 5} (5 total users)
Type     Name        # reqs  # fails |  Avg   Min   Max   Med | req/s  failures/s
GET      /                 294    0(0.00%) |    2     1     8     2 | 14.90        0.00
         Aggregated        294    0(0.00%) |    2     1     8     2 | 14.90        0.00

Response time percentiles (approximated)
Type   Name                50% 66% 75% 80% 90% 95% 98% 99% 99.9% 99.99% 100% # reqs
GET    /                      2   2   2   2   3   3   3   4    8     8     8  294

结论:--headless 压测正常,20 秒内 294 个请求,0 失败,P99 约 4ms。

三、卸载与清理

pip3 uninstall -y locust

同时可清理临时 locustfile 与 Python 缓存:

rm -f /opt/locustfile.py

四、常见问题(FAQ)

Q1:locust: command not found? 安装未成功或 PATH 不含 /usr/local/bin。确认 which locust 有路径,或用 python3 -m locust 调用。

Q2:pip3 下载 Locust 很慢/失败? 使用国内镜像:pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple locust。

Q3:--version 出现 greenlet is being finalized 异常正常吗? 正常。这是 gevent 退出时的已知日志噪音,版本号已在异常前打印,功能不受影响。

Q4:# reqs 很少正常吗? 默认 wait_time 会让用户间隔等待,压测量偏低属正常设计;要提高吞吐可把 wait_time 调小或改为 between(0, 0)。

Q5:如何指定压测目标? 命令行用 --host http://192.168.10.10/,或在 locustfile 里给 HttpUser 定义 host 属性。

五、参考链接