locust入门

简介:

locust是python语言的一个开源压测框架, 利用gevent协程来产生大量的并发. 官网: https://locust.io/

安装:

pip install locust

运行

  • master
locust -f lc.py --worker --master-host=127.0.0.1
  • worker
locust -f lc.py --worker --master-host=127.0.0.1
启动master之后访问 http://localhost:8089/即可看到主界面, 主界面配置和一些参数的解释:
  • Number of total users to simulate: 要模拟的用户总数

  • Spawn rate : 每秒产生的用户数,将多少用户添加到当前用户,直到用户总数

  • rps: 每秒请求数.doc

  • wait_time = between(0, 0) : 用于确定模拟用户在执行任务之间应等待多长时间 Doc

关于上面三个参数的解释:

例如:

Number of total users to simulate: 500

Spawn rate: 20

则脚本每秒产生20个用户,并一直到500个为止. 然后开始使用500个用户来产生并发, 预期的RPS应该在50左右

Demo脚本如下:

import requests
import json
import uuid
import time
from locust import between, task
from locust.contrib.fasthttp import FastHttpUser
import random

data = {
    "header": [["query"]],
    "data": [
        {"query": "后海大鲨鱼"},
        {"query": "没问题"},
        {"query": "送人的"},
    ],
}


class WebsiteUser(FastHttpUser):
    wait_time = between(5, 15)
    host = "http://nta-api-ks.leyanbot.com"
    
    def body(self):
        test_data = data["data"]
        _index = random.randint(0, len(test_data) - 1)
        q = test_data[_index]["query"]
        request_id = str(uuid.uuid4())
        text = {"text": q}
        # form user 随机
        # role 2、3 随机
        # to-user 跟坐席一致
        role_list = [2, 3]
        _role_list_index = random.randint(0, 1)
        
        body = {
            "requestId": request_id,
            "createTime": int(time.time()),
            "generator": 1,
            "type": 1,
            "fromUser": {"nickName": f"LcTestUser-{request_id}", "role": 1, "openId": "sth-ApiTest"},
            "toUser": {"nickName": "lc-test", "role": role_list[_role_list_index], "openId": ""},
            "message": {"contentType": 1, "content": json.dumps(text)},
            "context": {"sellerId": 1724795549, "itemId": 0},
            "assistantOnlineStatus": 1,
        }
        return body

    @task
    def ks(self):
        data = self.body()
        with self.client.post(
            "/agent/conversation/ks", catch_response=True, json=data
        ) as response:
            if response.status_code == 200:
                response.success()
            else:
                try:
                    _resp = response.json()
                except Exception:
                    _resp = {"msg": "get response json error"}
                print(f"nick_name:{data['fromUser']['nickName']},code:{response.status_code}. resp:{_resp}")
                response.failure(f"code is not 200:{response.status_code}")
                
    def on_stop(self):
        self.client.cookies.clear()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章