Swagger (现称OpenAPI) 是一套用于设计、构建、文档化和消费RESTful API的开源工具集,在Linux微服务架构中发挥着重要作用。
// 添加依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
// 配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerJsdoc = require('swagger-jsdoc');
const options = {
definition: {
openapi: '3.0.0',
info: {
title: '微服务API',
version: '1.0.0',
},
},
apis: ['./routes/*.js'], // 包含API注释的文件路径
};
const specs = swaggerJsdoc(options);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));
在API网关(如Kong, Nginx)层面统一集成Swagger UI,聚合所有微服务的API文档:
/services
├── user-service
│ └── swagger.json
├── order-service
│ └── swagger.json
└── product-service
└── swagger.json
# application.yml
springfox:
documentation:
swagger-ui:
enabled: true
oauth:
client-id: your-client-id
client-secret: your-client-secret
realm: your-realm
app-name: your-app-name
scope-separator: " "
additionalQueryStringParams: {}
@Profile("dev")
限定只在开发环境启用问题1:微服务API文档分散 - 解决方案:使用Swagger Hub或自建Swagger聚合服务
问题2:文档与实际API不一致 - 解决方案:将Swagger文档生成加入单元测试流程
问题3:大文档加载慢 - 解决方案:按微服务模块拆分文档,使用标签分组
Swagger作为微服务架构中的API管理工具,能显著提升开发效率、降低沟通成本,是现代微服务开发不可或缺的组成部分。