温馨提示×

linux swagger如何优化性能

小樊
38
2026-09-24 22:22:38
栏目: 智能运维

在 Linux 环境下使用 Swagger(如 Swagger UI / Swagger Editor / Springfox、springdoc-openapi 等) 时,性能问题通常出现在接口数量大、文档生成慢、UI 加载卡顿、服务器资源占用高等场景。下面从架构、配置、使用方式、运维几个层面系统讲如何优化。


一、服务端(文档生成)性能优化

1. 减少扫描范围(最重要)

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

2. 关闭不必要的文档细节

减少注解解析和模型展开:

.enableUrlTemplating(false)
.forCodeGeneration(false)

Springdoc:

springdoc:
  api-docs:
    enabled: true
  swagger-ui:
    disable-swagger-default-url: true

3. 使用 springdoc-openapi 替代 Springfox(强烈推荐)

对比 Springfox springdoc
性能 慢 ✅ 快
维护 停更 ✅ 活跃
Spring Boot 3 ❌ 不支持 ✅ 支持
<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
</dependency>

4. 缓存 OpenAPI JSON

Swagger UI 每次刷新都会请求 /v3/api-docs。

✅ 优化方式:

  • Nginx 缓存
  • 或定时生成静态 JSON 文件
location /v3/api-docs {
    proxy_cache swagger_cache;
    proxy_cache_valid 10m;
}

二、Swagger UI 性能优化(前端)

5. 使用静态 Swagger UI(而不是后端渲染)

最推荐方案(生产环境)

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"
});

✅ 优点:

  • 不占用 Java 内存
  • 启动快
  • 可 CDN 加速

6. 关闭深度展开 & 自动展开

docExpansion: "none",
defaultModelsExpandDepth: -1,
defaultModelExpandDepth: 1

7. 减少接口数量显示

  • 使用 tags 分组
  • 隐藏 model 定义
springdoc:
  swagger-ui:
    tags-sorter: alpha
    operations-sorter: method

三、Linux 服务器层面优化

8. 调整 JVM 参数

-Xms512m -Xmx1024m
-XX:+UseG1GC

9. 使用 Nginx 反向代理 + 压缩

gzip on;
gzip_types application/json text/html;

10. 生产环境关闭 Swagger

springdoc:
  swagger-ui:
    enabled: false

或使用 profile:

@Profile("dev")

四、常见性能问题速查表

问题 原因 解决方案
启动慢 扫描包太多 限制 basePackage
UI 卡 接口 500+ 静态 UI
内存高 Springfox 换 springdoc
JSON 大 Model 多 关闭 example
刷新慢 每次生成 缓存 JSON

五、推荐最佳实践(总结)

✅ 开发环境:springdoc + 局部扫描
✅ 测试环境:Swagger UI
✅ 生产环境:静态 JSON + Nginx


如果你能告诉我:

  • 用的是 Springfox / springdoc / 原生 Swagger
  • 接口数量级(100 / 1000+)
  • 是否生产环境

我可以给你更具体的配置示例。

0 踩