最近做系统性能调优,发现了一款比较好用的工具Locust。
简介
Locust 是非常简单易用,分布式,用户负载测试工具。Locust主要为网站或者其他系统进行负载测试,能测试出一个系统可以并发处理多少用户。
Locust 是完全基于时间的,因此单个机器支持几千个并发用户。相比其他许多事件驱动的应用,Locust 不使用回调,而是使用对协程支持比较完善的gevent(基于IO切换)。
特点
· 完全使用纯Python代码编写用户测试场景,不需要任何配置文件。
· 分布式&可伸缩 - 支持成千上万的用户
· 基于webui(自带)
· 可以测试任意系统
安装
pip install locustio
或者
easy_install locustio
检查是否安装成功;可以通过“locust --help”来检测。
文档说明
官方文档:http://docs.locust.io/en/latest/installation.html
简单示例
test.py
from locust import web, HttpLocust, TaskSet, events,task import random, traceback # 增加新的web界面 @web.app.route("/hi") def my_added_page(): return "hello locust..." # 钩子函数 def on_request_success(request_type, name, response_time, response_length): print 'Type: %s, Name: %s, Time: %fms, Response Length: %d' % \\ (request_type, name, response_time, response_length) def on_request_failure(request_type, name, response_time, exception): print 'Type: %s, Name: %s, Time: %fms, Reason: %r' % \\ (request_type, name, response_time, exception) events.request_success += on_request_success events.request_failure += on_request_failure class UserBehavior(TaskSet): def on_start(self): """ on_start is called when a Locust start before any task is scheduled """ self.login() def login(self): with self.client.post("/login", {"username":"ellen_key", "password":"education"}, catch_response = True) as r: if random.choice([0, 1]): r.success() else: r.failure('0') @task(2) def index(self): self.client.get("/") @task(1) def profile(self): self.client.get("/profile") class WebsiteUser(HttpLocust): # 指向一个TaskSet类,TaskSet类定义了每个用户的行为 task_set = UserBehavior # 请求等待最小时间min_wait和请求等待最大时间max_wait min_wait = 5000 max_wait = 9000 host = http://127.0.0.1 |
单机
终端输入:
locust -f test.py
webui访问地址:localhost:8089
ui界面需要填写两个参数:
number of users to simulate:模拟用户的数量
Hatch rate (users spawned/second):表示产生模拟用户的速度,每秒启动多少个用户
分布式
master机终端输入:
locust -f test.py --master --master-port=8888(默认的是8080端口)
salve机终端输入:
locust -f test.py --slave --master-host=<master-IP> --master-bind-host=8888