Linux环境下Swagger性能测试实施指南
在Linux系统上,首先需要安装Swagger相关工具以生成和查看API文档。常见步骤如下:
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
npm install -g swagger-jsdoc swagger-ui-express
@Api、@ApiOperation等注解),然后通过swag init命令生成swagger.json或swagger.yaml文档。Swagger UI提供了直观的交互界面,可用于快速测试API的基本性能(如响应时间):
./swagger.json):swagger serve --no-open ./swagger.json
http://localhost:8080(默认端口),找到目标接口,点击“Try it out”按钮,输入参数后发送请求。界面会显示响应时间(Response Time),可初步判断接口性能。若需模拟高并发场景、评估接口吞吐量(TPS/QPS)和系统稳定性,需结合Linux下的专业性能测试工具:
ab -n 100 -c 10 http://localhost:3000/api/v1/items
输出结果包含请求处理时间(Time per request)、**吞吐量(Requests per second)**等关键指标。siege -c 50 -t 1M http://localhost:3000/api/v1/items
结果会显示事务率(Transactions per second)、响应时间分布等。通过脚本实现性能测试的自动化,适合持续集成(CI)环境。示例(使用Shell脚本+ApacheBench):
#!/bin/bash
# 定义测试参数
URL="http://localhost:3000/api/v1/items"
CONCURRENCY=10
REQUESTS=100
# 执行性能测试
ab -n $REQUESTS -c $CONCURRENCY $URL > ab_result.txt
# 提取关键指标
echo "===== Performance Test Result =====" >> result.log
grep "Requests per second" ab_result.txt >> result.log
grep "Time per request" ab_result.txt >> result.log
将脚本加入cron定时任务,定期执行并记录性能数据,便于对比分析。