简介
Locust一款开源性能测试工具,易于使用、脚本化、可扩展,对开发者非常友好。
特性:
- 代码定义用户行为
不用笨重的UI或膨胀的XML,只要简单的代码。 - 分布式和可扩展
Locust支持在多台机器上运行分布式的负载测试,可以用来模拟数百万个并发用户。 - 深受考验
Locust已被用来模拟数百万个并发用户。Battlelog是一个通过网页发送游戏连接请求的应用,它使用Locust进行了负载测试,所以说Locust是Battletested (久经沙场)。
安装
pip install locust
初试
app.py
import json
import tornado.web
import tornado.ioloop
LOGIN = False # 是否登录
def fib(n):
"""计算斐波那契数列的第n项"""
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
class LoginHandler(tornado.web.RequestHandler):
def post(self):
body = self.request.body
body = json.loads(body)
username = body.get("username")
password = body.get("password")
if username == "foo" and password == "bar":
global LOGIN
LOGIN = True
self.write("Welcome!")
else:
self.set_status(400)
class IndexHandler(tornado.web.RequestHandler):
def get(self):
if LOGIN:
self.write("Hello World!")
else:
self.set_status(400)
class ItemHandler(tornado.web.RequestHandler):
def get(self):
id = self.get_argument("id")
id = int(id)
self.write(str(fib(id)))
if __name__ == "__main__":
print("http://localhost:8888")
app = tornado.web.Application([
(r"/login", LoginHandler),
(r"/hello", IndexHandler),
(r"/world", IndexHandler),
(r"/item", ItemHandler),
])
app.listen(8888)
tornado.ioloop.IOLoop.instance().start()
locustfile.py
import time
from locust import HttpUser, task, between
class QuickstartUser(HttpUser):
host = "http://localhost:8888" # 访问的站点,最后不要加斜杠
wait_time = between(1, 2)
@task
def index_page(self):
self.client.get("/hello")
self.client.get("/world")
@task(3)
def view_item(self):
for item_id in range(10):
self.client.get(f"/item?id={item_id}", name="/item")
time.sleep(1)
def on_start(self):
self.client.post("/login", json={"username": "foo", "password": "bar"})
启动Locust:locust
若需指定路径:locust -f locust_files/my_locust_file.py
访问http://localhost:8089/,模拟用户数设为100,每秒产生用户设为10,开始
结果
遇到的坑
- 无法访问http://0.0.0.0:8089/
关闭科学上网工具,尝试访问http://localhost:8089/。 - 接口运行正确但没有图表出来
如本人使用360浏览器,切换至极速模式即可。