在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;)。