locust本机分布式运行

Posted by Tesla9527 on May 17, 2022

例子如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from locust import FastHttpUser, task


class User(FastHttpUser):
    host = "your_host"

    @task
    def index(self):
        with self.client.get("/xxx",catch_response=True) as rp:
            if rp.status_code == 200:
                rp.success()
            else:
                rp.failure(f"出现了错误: {rp.status_code} - {rp.text}")

    def on_start(self):
    # 虚拟用户启动Task时运行
        print('start 虚拟用户启动Task时运行')
 
    def on_stop(self):
    # 虚拟用户结束Task时运行
        print('end 虚拟用户结束Task时运行')
        self.environment.runner.quit()


if __name__ == "__main__":
    import os
    import multiprocessing
    import requests
    from datetime import datetime

    print("开始运行压测!")
    current_file_name = os.path.basename(__file__)
    os.system(f'start locust -f {current_file_name} --master')
    for i in range(multiprocessing.cpu_count()):
        os.system(f'start locust -f {current_file_name} --worker')

    print(f"开始计时 - {datetime.now()}")
    from threading import Timer
    def stop():
        print(f"停止运行压测! - {datetime.now()}")
        rp = requests.get(url="http://localhost:8089/stop")
        print(f"{rp.status_code} - {rp.text}")
    time = "00:20:00"  # in n seconds stop the runner
    run_time = sum(x * int(t) for x, t in zip([3600, 60, 1], time.split(":"))) 
    t = Timer(run_time, stop)
    t.start()

这样启动之后,本机输入http://localhost:8089就可以进入web页面了。

但有时候我们想通过本机ip+端口的方式打开,这样方便局域网内的其他机器访问。

改动点:

1
os.system(f'start locust -f {current_file_name} --master --web-host=0.0.0.0')
1
os.system(f'start locust -f {current_file_name} --worker --master-host=your_ip')
1
rp = requests.get(url="http://your_ip:8089/stop")