簡介:
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()