在 Linux 环境下使用 Swagger(如 Swagger UI / Springfox / springdoc-openapi) 时,如果出现加载慢、响应慢,一般可以从下面几个方向排查和优化。
Spring 项目在启动或访问 Swagger 时,会扫描所有 Controller。
表现
解决 ✅ 限制扫描范围:
@EnableOpenApi
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
springdoc:
packages-to-scan: com.example.controller
paths-to-match: /api/**
或 Springfox:
.select()
.basePackage("com.example.controller")
.build();
Swagger UI 默认可能从 CDN 加载 JS/CSS。
表现
swagger-ui-bundle.js解决 ✅ 使用本地 Swagger UI(推荐)
springdoc 本地化
<dependency>
<groupId>org.webjars</groupId>
<artifactId>swagger-ui</artifactId>
</dependency>
或 Nginx 代理 CDN:
location /swagger-ui/ {
proxy_pass https://cdn.jsdelivr.net/;
}
Linux 服务器配置低时,Swagger 生成文档会非常吃 CPU。
解决 ✅ 增加 JVM 内存:
-Xms512m -Xmx1024m
✅ 关闭 Swagger(生产环境强烈建议):
springdoc:
swagger-ui:
enabled: false
或:
@Profile("!prod")
Swagger 会递归解析对象。
解决 ✅ 忽略不必要字段:
@Schema(hidden = true)
private String internalField;
✅ 使用 DTO 而不是 Entity
有时 Swagger UI 卡住是因为:
验证
curl -I https://cdn.jsdelivr.net
解决
例如:
/swagger-ui.html 被拦截解决
.antMatchers(
"/swagger-ui/**",
"/v3/api-docs/**"
).permitAll()
# 看 CPU
top
# 看接口耗时
curl -w "%{time_total}\n" http://localhost:8080/v3/api-docs
# 看是否被墙
curl https://cdn.jsdelivr.net
❌ 不要长期开 Swagger
✅ 用 dev / test 环境开启
✅ 或用 Knife4j(国内更快)
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-spring-boot-starter</artifactId>
</dependency>
如果你愿意,可以告诉我:
我可以直接给你针对性配置。