【问题标题】:Locust report /stats/requests data to other user interfaceLocust 向其他用户界面报告 /stats/requests 数据
【发布时间】:2021-10-25 16:46:28
【问题描述】:

我发现 Locust UI 会从 http://my-locust-server/stats/requests 端点获取数据,并绘制图表。例如Total request per SecondResponse TimeNumber of Users

我想将/stats/requests 数据发送到另一台服务器以进行绘图。如何在locustfile.py 中做到这一点?

以下代码不起作用,仅用于演示目的。

from locust import HttpUser, task, events
import requests

class User(HttpUser):

    @task
    def scenario_01(self):
        self.client.get('/some_endpoint')

# ==========
# following codes won't work, will block the whole locust.
# ==========
import time
starttime = time.time()
while True:
    r = requests.get('http://my-locust-server/stats/requests')
    payload = r.json()
    requests.post('http://another-server-for-plotting', json=payload)
    time.sleep(5.0 - ((time.time() - starttime) % 5.0))

现在我能想到的是运行另一个程序来获取和报告数据。但是如何在一个locustfile.py 中做到这一点。

谢谢!

【问题讨论】:

    标签: python locust


    【解决方案1】:

    导入此模块后,while True 代码将被评估并永远运行。如果您希望该循环在后台运行,您可以使用 python threading 库。将该 while 循环放在一个可调用函数中,然后将该函数传递给一个新的 Thread 对象并在导入时启动该线程。

    from locust import HttpUser, task, events
    import requests
    
    class User(HttpUser):
    
        @task
        def scenario_01(self):
            self.client.get('/some_endpoint')
    
    def backgroundloop():
        while True:
            import time
            starttime = time.time()
            r = requests.get('http://my-locust-server/stats/requests')
            payload = r.json()
            requests.post('http://another-server-for-plotting', json=payload)
            time.sleep(5.0 - ((time.time() - starttime) % 5.0))
    
    import threading
    t = threading.Thread(target=backgroundloop)
    t.start()
    

    【讨论】:

      【解决方案2】:

      或者,您可以使用 Locust 的 Event Hooks 直接发送数据,而无需从网络路由中获取数据。如果您在分布式模式下运行,worker_report 可能是最好的。不完整的例子:

      from locust import events
      import requests
      
      
      @events.worker_report.add_listener
      def send_data_off_somewhere(client_id, data):
          requests.post('http://another-server-for-plotting', json=data)
      

      【讨论】:

      • 感谢您的信息!知道worker_report 被解雇的频率有多高吗? @Solowalker
      • 每次master收到worker的report。每个worker向master汇报2-3秒。
      猜你喜欢
      • 2021-03-12
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-15
      相关资源
      最近更新 更多