在 Linux 环境下使用 Swagger(如 Swagger UI / Swagger Editor / Springfox、springdoc-openapi 等) 时,性能问题通常出现在接口数量大、文档生成慢、UI 加载卡顿、服务器资源占用高等场景。下面从架构、配置、使用方式、运维几个层面系统讲如何优化。
Swagger 启动慢,90% 是因为扫描了过多包。
Springfox 示例
springfox:
documentation:
swagger:
enabled: true
@EnableSwagger2
@SpringBootApplication
public class App {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.api")) // 只扫接口包
.paths(PathSelectors.any())
.build();
}
}
✅ 建议:
controller 以外的包springframework、第三方 SDK减少注解解析和模型展开:
.enableUrlTemplating(false)
.forCodeGeneration(false)
Springdoc:
springdoc:
api-docs:
enabled: true
swagger-ui:
disable-swagger-default-url: true
| 对比 | Springfox | springdoc |
|---|---|---|
| 性能 | 慢 | ✅ 快 |
| 维护 | 停更 | ✅ 活跃 |
| Spring Boot 3 | ❌ 不支持 | ✅ 支持 |
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
</dependency>
Swagger UI 每次刷新都会请求 /v3/api-docs。
✅ 优化方式:
location /v3/api-docs {
proxy_cache swagger_cache;
proxy_cache_valid 10m;
}
最推荐方案(生产环境)
wget https://github.com/swagger-api/swagger-ui/archive/refs/tags/v5.x.zip
部署到 Nginx:
server {
listen 80;
root /opt/swagger-ui;
index index.html;
}
前端配置:
const ui = SwaggerUIBundle({
url: "/static/api-docs.json",
dom_id: "#swagger-ui",
deepLinking: false,
docExpansion: "none"
});
✅ 优点:
docExpansion: "none",
defaultModelsExpandDepth: -1,
defaultModelExpandDepth: 1
tags 分组springdoc:
swagger-ui:
tags-sorter: alpha
operations-sorter: method
-Xms512m -Xmx1024m
-XX:+UseG1GC
gzip on;
gzip_types application/json text/html;
springdoc:
swagger-ui:
enabled: false
或使用 profile:
@Profile("dev")
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 启动慢 | 扫描包太多 | 限制 basePackage |
| UI 卡 | 接口 500+ | 静态 UI |
| 内存高 | Springfox | 换 springdoc |
| JSON 大 | Model 多 | 关闭 example |
| 刷新慢 | 每次生成 | 缓存 JSON |
✅ 开发环境:springdoc + 局部扫描
✅ 测试环境:Swagger UI
✅ 生产环境:静态 JSON + Nginx
如果你能告诉我:
我可以给你更具体的配置示例。