我需要一个例子或解释,如何使用自定义客户端编写蝗虫负载测试 (在我的情况下是 WebSocket 服务器)。我看到了在蝗虫文档中给出的解释,但我不明白这些函数 __getattr__
和 def wrapper(*args, **kwargs):
是如何通过蝗虫触发钩子事件的。
今天我在尝试这个内容时也发现自定义示例有些棘手,因为很难确定魔法发生的位置。这里是一个更简单的客户端、任务和用户交互版本。不再使用装饰器来拦截客户端的任意方法,而是只能完成一项任务,这样您就可以看到时间和错误处理所发生的位置以及如何使用Locust事件钩子来发送成功和失败。
import time
from locust import TaskSet, task, Locust, events
class SimpleClient(object):
def __init__(self):
pass
def execute(self, name):
start_time = time.time()
try:
print("do your things cause stress and throw exceptions here.")
time.sleep(1)
except Exception as e:
total_time = int((time.time() - start_time) * 1000)
events.request_failure.fire(request_type="execute", name=name, response_time=total_time, exception=e)
else:
total_time = int((time.time() - start_time) * 1000)
events.request_success.fire(request_type="execute", name=name, response_time=total_time, response_length=0)
class SimpleTasks(TaskSet):
@task
def simple_task(self):
self.client.execute('simple_things')
class SimpleUser(Locust):
def __init__(self, *args, **kwargs):
super(Locust, self).__init__(*args, **kwargs)
self.client = SimpleClient()
task_set = SimpleTasks
min_wait = 1000
max_wait = 10000
然后你可以在终端中运行以下命令:
locust -f simple_test.py --no-web --clients=2 --hatch-rate=2 --num-request=4 --print-stats --only-summary