简介与功能
Locust 是基于Gevent协程实现,可以轻量高效地单机模拟较高并发请求。
主要功能:
- 基于Web的用户界面,用户可以实时监控脚本运行状态
- 分布式和可扩展,支持成千上万的用户
- 几乎可以测试任何系统,除了web接口外,还可自定义clients测试其他类型系统
安装
- Python 的编译安装
源码下载:(下载gz)
https://www.python.org/downloads/source/
tar -zxvf Python-3.6.9.tgz
cd Python-3.6.9
./configure –prefix=your_python_dir(你准备安装的路径,在该路径下会生成bin,lib文件夹,如为/home/username/bin/python36/)
make && make install
- 安装虚拟环境及依赖
virtualenv locust_example --no-site-packages
source locust_env/bin/activate
pip install locust
示例程序
test.py
from locust import HttpLocust, TaskSet, task, between
class UserBehavior(TaskSet):
def on_start(self):
""" on_start is called when a Locust start before any task is scheduled """
self.login()
def on_stop(self):
""" on_stop is called when the TaskSet is stopping """
self.logout()
def login(self):
self.client.post("/login", {"username":"ellen_key", "password":"education"})
def logout(self):
self.client.post("/logout", {"username":"ellen_key", "password":"education"})
@task(2)
def index(self):
self.client.get("/")
@task(1)
def profile(self):
self.client.get("/profile")
class WebsiteUser(HttpLocust):
task_set = UserBehavior
wait_time = between(5, 9)
执行命令
locust -f test.py --host=http://example.com --web-host=172.28.249.18
注:在Linux系统多网卡情况下,Locust自动选择网卡时可能会遇到error: [Errno 97] Address family not supported by protocol错误,此时可以通过直接指定web host来解决问题,使用选项--web-host来指定可用的地址,例:locust -f xxx.py --web-host=127.0.0.1
结果输出:
在浏览器里打开:http://your_ip:8089
点击开始
Charts标签下有具体的图表,包括请求数的变化、响应时间的变化、并发用户数的变化。