1. from gevent import monkey
    2. monkey.patch_all()
    3. import time
    4. from locust import TaskSet, task, constant_throughput, wait_time
    5. from locust.contrib.fasthttp import FastHttpUser
    6. from logzero import logger
    7. class NotifyMsgApi(TaskSet):
    8. def on_start(self):
    9. self.headers = {
    10. "Adapter-data": 'xxxx'
    11. }
    12. @task
    13. def notify_msg(self):
    14. params = {
    15. "moduleType": "SHARE",
    16. "moduleType": "LIVE",
    17. "moduleType": "ALIGN",
    18. }
    19. start = time.perf_counter()
    20. assert_data = ""
    21. with self.client.get(
    22. "/msg", headers=self.headers, params=params, catch_response=True, name="msg") as response:
    23. if response.status_code == 200:
    24. response.success()
    25. # logger.info(response.json())
    26. else:
    27. response.failure()
    28. logger.info(response.text)
    29. assert_data = response.json().get('logId')
    30. all_time = (time.perf_counter() - start) * 1000
    31. if int(all_time) > 1000:
    32. logger.info(f"all_time: {all_time}-- {assert_data}")
    33. class UserTest(FastHttpUser):
    34. host = "http://xxxx:8906"
    35. wait_time = constant_throughput(1.1)
    36. tasks = [NotifyMsgApi]
    37. if __name__ == "__main__":
    38. """
    39. ps -ef | grep locust | grep -v grep | grep msg_perf.py | awk '{print $2}' | xargs kill -9
    40. """
    41. import os
    42. from threading import Timer
    43. import requests
    44. import json
    45. file_name = os.path.abspath(__file__)
    46. logger.info("##################启动新压测进程########################")
    47. os.system(f"nohup locust -f {file_name} --web-host=0.0.0.0 --master -P 8086 &")
    48. for i in range(5):
    49. os.system(f"nohup locust -f {file_name} --web-host=0.0.0.0 --worker &")
    50. def stop():
    51. logger.info("停止运行压测任务")
    52. response = requests.get("http://x.x.x.x:8086/stop")
    53. logger.info(f"operate stop perf task api: {response.text}")
    54. logger.info("##################kill 进程########################")
    55. if json.loads(response.text)["success"]:
    56. os.system(
    57. "nohup ps -ef | grep locust | grep -v grep | grep %s | awk '{print $2}' | xargs kill -9 &" % file_name
    58. )
    59. time = "00:30:20" # 设置压测时间
    60. run_time = sum(x * int(t) for x, t in zip([3600, 60, 1], time.split(":")))
    61. logger.info(f"perf task run_time: {run_time}")
    62. t = Timer(run_time, stop)
    63. t.start()