背景
from fastapi import FastAPI
from pydantic import BaseModel
# 定义数据模型
class UserInput(BaseModel):
input: str
app = FastAPI()
controller = ChatController()
@app.post("/chat/")
def chat(user_input: UserInput):
result = controller.run(user_input.input)
return {
"result": result}
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8991)
run里面运行了一个服务,如何测试这个服务的抗压能力?
解决方案
要测试 FastAPI 服务的抗压能力,可以使用压力测试工具,如 locust、Apache Benchmark、JMeter、wrk 或 hey。这些工具可以模拟多个用户同时向服务器发送请求,帮助评估系统的负载能力和响应时间。
下面介绍一种简单的工具 hey 来测试这个 FastAPI 服务的抗压能力。
- 使用 hey 进行压力测试
安装 hey
hey 是一个轻量级的 HTTP 压力测试工具,可以通过以下命令进行安装:
macOS(使用 Homebrew):
brew install hey
Linux 或 Windows,可以从官方 GitHub 页面下载二进制文件并安装: https://github.com/rakyll/hey
运行压力测试
假设 FastAPI 服务运行在 http://localhost:8991,测试 /chat/ 端点。可以使用以下命令执行压力测试:
hey -n 1000 -c 50 -m POST -H "Content-Type: application/json" -d '{"input": "Hello, world!"}' http://localhost:8991/chat/
-n 1000:总请求数(此处设置为 1000)。
-c 50:并发数(同时进行的请求数为 50)。
-m POST:请求方法为 POST。
-H “Content-Type: application/json”:设置请求头,表示发送的是 JSON 数据。
-d ‘{“input”: “Hello, world!”}’:发送的请求数据。
http://localhost:8991/chat/:服务的 URL。
2. 使用 locust 进行压力测试
locust 是一个流行的开源负载测试工具,支持 Python 脚本编写用户行为。
安装 locust
可以通过 pip 安装:
pip install locust
编写测试脚本 locustfile.py
创建一个名为 locustfile.py 的文件,内容如下:
from locust import HttpUser, TaskSet, task, between
class UserBehavior(TaskSet):
@task
def chat(self):
self.client.post("/chat/", json={
"input": "Hello, world!"})
class WebsiteUser(HttpUser):
tasks = [UserBehavior]
wait_time = between(1, 3) # 每个用户等待 1 到 3 秒之间
def on_start(self):
"""在测试开始时运行,模拟用户初始化"""
pass
运行 locust
启动 locust:
locust -f locustfile.py --host=http://localhost:8991
然后在浏览器中访问 http://localhost:8089,可以设置并发用户数和请求速率来进行压力测试。
总结
通过 hey 或 locust 这样的工具,可以轻松模拟大量并发请求,测试 FastAPI 服务的抗压能力。