在Debian上进行Swagger API性能测试的完整流程
系统环境配置
确保Debian系统已更新至最新版本,并安装基础工具包:
sudo apt update && sudo apt upgrade -y
sudo apt install curl wget git -y
若需监控系统资源,可额外安装sysstat(包含iostat、vmstat等工具):
sudo apt install sysstat -y
部署Swagger环境
Swagger有两种常见使用场景:Swagger UI(文档展示与手动测试)和后端API框架集成(如Springdoc OpenAPI)。根据需求选择:
sudo apt install nodejs npm -y
npm install -g @swagger-api/swagger-ui
swagger-ui serve ./swagger.json # 启动服务,默认端口8080
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version> <!-- 使用最新稳定版 -->
</dependency>
启动Spring Boot应用后,访问http://localhost:8080/swagger-ui.html查看文档。根据测试需求选择合适的工具,覆盖从基础到高级的场景:
基础工具(快速验证)
/api/users接口,100并发,1000次请求):ab -n 1000 -c 100 http://your-server-ip/api/users
urls.txt中的接口,20并发,30秒持续时间):siege -c 20 -t 30s -f urls.txt
高级工具(自动化与深度分析)
wget https://dlcdn.apache.org/jmeter/binaries/apache-jmeter-5.6.3.tgz./apache-jmeter-5.6.3/bin/jmeterBasicSimulation.scala):class BasicSimulation extends Simulation {
val scn = scenario("Swagger API Test")
.exec(http("Get Users")
.get("http://your-server-ip/api/users"))
.pause(1)
setUp(scn.inject(atOnceUsers(100)).protocols(httpProtocol))
}
运行命令:./gatling.sh -s BasicSimulationtest.js):import http from 'k6/http';
import { check } from 'k6';
export default function () {
let res = http.get('http://your-server-ip/api/users');
check(res, { 'status is 200': (r) => r.status === 200 });
}
运行命令:k6 run --vus 100 --duration 30s test.js基础测试(以Apache Bench为例)
测试Swagger UI的/v3/api-docs接口(获取OpenAPI规范):
ab -n 500 -c 50 http://your-server-ip/v3/api-docs
关键指标解读:
高级测试(以JMeter为例)
http://your-server-ip/api/users)。结果分析
top查看CPU使用率、iostat查看磁盘IO、vmstat查看内存)判断瓶颈所在。优化措施
/etc/sysctl.conf):增加文件描述符限制(fs.file-max=65535)、优化TCP参数(net.ipv4.tcp_tw_reuse=1)。apt autoremove删除无用软件包,apt clean清理缓存。nginx.conf中添加expires 1h;)。nginx.conf中添加gzip on; gzip_types text/plain application/json;)。