在 Debian 上利用 Swagger 进行 API 性能测试
一、思路与工具选择
二、准备可测试的 API 规范与 Mock 服务
openapi: 3.0.0
info:
title: Demo API
version: 1.0.0
paths:
/ping:
get:
summary: 健康检查
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
properties:
message:
type: string
sudo apt-get update && sudo apt-get install -y docker.io
sudo systemctl start docker && sudo systemctl enable docker
# Swagger Editor
docker pull swaggerapi/swagger-editor:v4.6.0
docker run -d -p 38080:8080 swaggerapi/swagger-editor:v4.6.0
# Swagger UI(将宿主机的 /path/to/spec 挂载到容器内 /spec)
docker pull swaggerapi/swagger-ui:v4.15.5
docker run -d -p 38081:8080 -e SWAGGER_JSON=/spec/openapi.yaml -v /path/to/spec:/spec swaggerapi/swagger-ui:v4.15.5
访问 http://localhost:38080(Editor)导入规范,http://localhost:38081(UI)查看与调试。sudo apt-get update && sudo apt-get install -y nodejs npm
npm install swagger-ui-express
用 Express 加载规范并启动服务,便于在本地对接被测服务或 Mock。三、基于规范的性能测试流程
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 379CE192D401AB61
echo "deb https://dl.k6.io/deb stable main" | sudo tee /etc/apt/sources.list.d/k6.list
sudo apt-get update && sudo apt-get install -y k6
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
vus: 50, // 并发用户数
duration: '30s', // 持续时间
thresholds: {
http_req_duration: ['p(95)<500'], // 95% 请求 < 500ms
http_req_failed: ['rate<0.01'], // 错误率 < 1%
},
};
export default function () {
const res = http.get('http://<your-api-host>/ping');
check(res, { 'status is 200': (r) => r.status === 200 });
sleep(0.1);
}
k6 run test.js
sudo apt-get install -y apache2-utils
ab -n 10000 -c 100 http://<your-api-host>/ping
sudo apt-get install -y siege
siege -c 100 -t 30s http://<your-api-host>/ping
top/htop # CPU/内存
vmstat 1 # 上下文切换、系统负载
iostat -x 1 # 磁盘 IO
netstat -s # 网络统计
free -m # 内存使用
四、结果分析与优化建议