针对 Swagger(OpenAPI)在 Linux 服务器上的“优化”,通常可以从 性能、内存、访问安全、文档体积、部署方式 等几个维度来做。下面按常见场景给你一套实用优化方案。
如果你用的是 Spring Boot + Swagger / springdoc-openapi:
springdoc:
api-docs:
enabled: false # 线上关闭 /v3/api-docs
swagger-ui:
enabled: false # 线上关闭 swagger-ui
或按环境控制:
spring:
profiles: prod
springdoc:
api-docs:
enabled: false
✅ 效果:减少反射、JSON 生成、内存占用
@OpenAPIDefinition(
info = @Info(title = "API", version = "1.0")
)
public class OpenApiConfig {
@Bean
public GroupedOpenApi publicApi() {
return GroupedOpenApi.builder()
.group("public")
.pathsToMatch("/api/**")
.build();
}
}
❌ 避免扫描:
/actuator/**/error✅ 效果:
@Schema(hidden = true)
public class InternalModel {
private String secret;
}
或:
@JsonIgnore
private String password;
✅ 减少无用字段序列化
springdoc:
model-converters:
deprecating-converter:
enabled: false
或 Java:
springdoc.api-docs.enabled=false
不要直接访问后端 Swagger
✅ 做法:
/v3/api-docsserver {
listen 80;
server_name api.example.com;
location /swagger/ {
root /usr/share/nginx/html;
index index.html;
}
location /v3/api-docs {
proxy_pass http://127.0.0.1:8080;
}
}
✅ 好处:
ulimit -n 65535
/etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
✅ 方案一:Nginx 拦截
location /swagger-ui {
deny all;
}
✅ 方案二:Spring Security
@Override
protected void configure(HttpSecurity http) {
http
.authorizeRequests()
.antMatchers("/swagger-ui/**", "/v3/api-docs/**")
.hasRole("ADMIN");
}
-Xms512m
-Xmx1024m
-XX:+UseG1GC
✅ 避免频繁 Full GC
如果你只是 内部文档 / 对外接口说明:
| 场景 | 建议 |
|---|---|
| 性能敏感 | 只保留 /v3/api-docs |
| 对外 API | 用 Apifox / YApi |
| 高并发 | 完全关闭 Swagger UI |
| 微服务 | 用 Gateway 聚合文档 |
✅ 是否只在 dev / test 开启 Swagger
✅ 是否扫描了不必要的接口
✅ 是否用 Nginx 托管 UI
✅ 是否关闭 example / model 自动生成
✅ 是否限制访问权限
你可以直接贴: