目录
前言
- 一定数量的用户,同时并发请求某个接口,这时就会用到集合点,下面一起来学习下locust设置集合点
代码示例
# -*- coding: utf-8 -*-
# @Time : 2021/4/19
# @Author : 大海
import os
from locust import TaskSet, task, events, HttpUser
from gevent._semaphore import BoundedSemaphore
all_locusts_spawned = BoundedSemaphore()
all_locusts_spawned.acquire()
def on_hatch_complete(**kwargs):
# 创建钩子方法
all_locusts_spawned.release()
# 挂在到locust钩子函数(所有的Locust示例产生完成时触发)
# events.hatch_complete += on_hatch_complete # 1.0之前的写法
events.spawning_complete.add_listener(on_hatch_complete) # 1.0之后的写法
class TestTask(TaskSet):
def on_start(self):
"""所有任务启动前执行"""
all_locusts_spawned.wait()
print('所有任务启动前执行')
@task(1)
def index(self):
all_locusts_spawned.wait()
url = 'https://www.baidu.com'
self.client.get(url)
print('index task')
@task(1)
def login(self):
all_locusts_spawned.wait()
self.client.get("http://www.baidu.com")
print('login task')
# class MyUser(HttpLocust): 这是1.0之前写法
class MyUser(HttpUser):
# task_set = TestTask 这是1.0之前写法
tasks = [TestTask]
host = "http://www.baidu.com"
min_wait = 1000
max_wait = 3000
if __name__ == '__main__':
file_path = os.path.abspath(__file__)
os.system(f'locust -f {file_path} --web-host=127.0.0.1')