Swagger是一个流行的API文档工具,但在Linux环境下可能会遇到性能问题。以下是一些优化建议:
# 对于Node.js的Swagger UI Express
NODE_ENV=production node app.js
# 对于Java Spring Boot
spring.profiles.active=prod
# Nginx配置示例
location /swagger-ui/ {
expires 1y;
add_header Cache-Control "public";
# 其他配置...
}
# Nginx启用gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript;
// 只加载必要组件
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, {
customCss: '.swagger-ui .topbar { display: none }',
customSiteTitle: "My API Docs",
customfavIcon: "/favicon.ico"
}));
<!-- 替换本地资源为CDN版本 -->
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui.css">
# 移除不必要的描述和示例
paths:
/users:
get:
summary: "获取用户列表"
description: "" # 如果不需要详细描述可以移除
responses:
'200':
description: "成功"
// 对于大型API,考虑分拆文档
const fs = require('fs');
const { merge } = require('lodash');
const baseDoc = JSON.parse(fs.readFileSync('base.json'));
const userDoc = JSON.parse(fs.readFileSync('users.json'));
const completeDoc = merge({}, baseDoc, userDoc);
# 检查当前限制
ulimit -n
# 临时增加限制
ulimit -n 65536
# 永久修改
echo "* soft nofile 65536" >> /etc/security/limits.conf
echo "* hard nofile 65536" >> /etc/security/limits.conf
# 增加TCP缓冲区大小
sysctl -w net.core.rmem_max=16777216
sysctl -w net.core.wmem_max=16777216
sysctl -w net.ipv4.tcp_rmem="4096 87380 16777216"
sysctl -w net.ipv4.tcp_wmem="4096 65536 16777216"
# 使用htop监控资源使用
htop
# 使用ab进行压力测试
ab -n 1000 -c 100 http://localhost:3000/api-docs/
# 使用curl测试响应时间
curl -w "\nResponse time: %{time_total}s\n" http://localhost:3000/api-docs/
通过以上优化措施,可以显著提升Linux环境下Swagger的性能表现。根据您的具体使用场景,可以选择适合的优化方案组合使用。