JobPlus知识库 IT 大数据 文章
使用Locust快速完成高并发测试

简介

Locust是一款易于使用的分布式用户负载测试工具。它用于对网站(或其他系统)进行负载测试,并确定系统可以处理多少并发用户。

特点

  1. 使用python编写测试脚本
  2. 支持模拟数十万用户
  3. 基于web的操作界面
  4. 可以测试任何网站

安装

系统centos 7

pip install locustio

示例代码

  1. from locust import HttpLocust, TaskSet, task

  2. class UserBehavior(TaskSet):

  3.     def on_start(self):

  4.         """ on_start is called when a Locust start before any task is scheduled """

  5.         self.login()

  6.     def on_stop(self):

  7.         """ on_stop is called when the TaskSet is stopping """

  8.         self.logout()

  9.     def login(self):

  10.         self.client.post("/login", {"username":"ellen_key", "password":"education"})

  11.     def logout(self):

  12.         self.client.post("/logout", {"username":"ellen_key", "password":"education"})

  13.     @task(2)

  14.     def index(self):

  15.         self.client.get("/")

  16.     @task(1)

  17.     def profile(self):

  18.         self.client.get("/profile")

  19. class WebsiteUser(HttpLocust):

  20.     weight = 1

  21.     task_set = UserBehavior

  22.     min_wait = 5000

  23.     max_wait = 9000

  24.     host=https://google.com 

  25.     

  26. class MobileUserLocust(HttpLocust):

  27.     weight = 3

  28.     task_set = UserBehavior

  29.     min_wait = 5000

  30.     max_wait = 9000 

  31.     host=https://google.com 

Locust类参数(MobileUserLocust)

  • task_set:指定定义用户行为的类,包含一组任务
  • min_wait:最小的等待时间,毫秒
  • max_wait:最大的等待时间,毫秒 两者为声明则默认为1秒
  • host:加载的主机的URL前缀
  • weight:运行的次数比例

TaskSet类参数

@task(1):任务装饰器,参数为运行次数的比例

TaskSequence类

TaskSequence类是一个TaskSet,但它的任务将按顺序执行.

  1. from locust import TaskSequence, task

  2. class MyTaskSequence(TaskSequence):

  3.     @seq_task(1)

  4.     def first_task(self):

  5.         pass

  6.     @seq_task(2)

  7.     def second_task(self):

  8.         pass

  9.     @seq_task(3)

  10.     @task(10)

  11.     def third_task(self):

  12.         pass

在上面的示例中,顺序被定义为执行first_task,然后执行second_task,最后执行third_task 10次

启动测试

  1. //启动指定文件

  2. locust -f ./locust_test.py

  3. //启用2个locust

  4. locust -f locust_file.py WebUserLocust MobileUserLocust

打开测试界面

http://127.0.0.1:8089  你的服务器IP,本地则为localhost或者127.0.0.1


如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

¥ 打赏支持
153人赞 举报
分享到
用户评价(0)

暂无评价,你也可以发布评价哦:)

扫码APP

扫描使用APP

扫码使用

扫描使用小程序