【问题标题】:Centralized Swagger/OpenAPI UI for all the different microservices on a single swagger URL i.e accessing all the URLs through one集中式 Swagger/OpenAPI UI,用于单个 swagger URL 上的所有不同微服务,即通过一个 URL 访问所有 URL
【发布时间】:2022-01-28 01:19:39
【问题描述】:
【问题讨论】:
标签:
spring-boot
swagger
microservices
openapi
【解决方案1】:
如果所有 µservice 都使用相同的主机,您可以使用 spring-doc 创建一个充当 openAPI 网关的 Spring Boot µservice。 (如果他们没有使用同一个主机,你将不得不处理 CORS 问题)
- 首先,将以下依赖项添加到您的新网关 µservice
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 然后,添加以下配置
springdoc:
api-docs:
enabled: true
swagger-ui:
configUrl: ${server.servlet.contextPath}/v3/api-docs/swagger-config
url: ${server.servlet.contextPath}/v3/api-docs
urls:
- name: api-customer
url: /customer/v3/api-docs
- name: api-cart
url: /cart/v3/api-docs
- name: api-product
url: /product/v3/api-docs
对于每个 µservice,您必须使用 json 或 yaml 格式的 openAPI 定义的 url 填写 url 属性。
对于使用 openAPI 3.0 的 springdoc 库,默认 url 是 /${µServiceContextPath}/v3/api-docs
对于使用 openAPI 2.0 的 springfox 库,默认 url 是 /${µServiceContextPath}/v2/api-docs
- 最后访问/${contextPath}/swagger-ui.html,你就可以选择一个openAPI了
【解决方案2】:
我在GitHub 上找到了一个可行的解决方案。它适用于 Spring Cloud Discovery,但可以轻松适应其他发现解决方案。基本思想是为 Swagger 生成指向 OpenAPI JSON 文件的 URL 列表。
结果与@shadyx 的答案类似,但列表是动态生成的
@RestController
public class SwaggerUiConfig {
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/swagger-config.json")
public Map<String, Object> swaggerConfig() {
List<SwaggerUrl> urls = new LinkedList<>();
discoveryClient.getServices().forEach(serviceName ->
discoveryClient.getInstances(serviceName).forEach(serviceInstance ->
urls.add(new SwaggerUrl(serviceName, serviceInstance.getUri() + "/v3/api-docs"))
)
);
return Map.of("urls", urls);
}
}
应用程序.yaml
springdoc:
swagger-ui:
configUrl: "/swagger-config.json"
生成的swagger-config.json示例
{
"urls": [
{
"url": "http://localhost:8088/v3/api-docs/users",
"name": "users"
},
{
"url": "http://localhost:8088/v3/api-docs/stores",
"name": "stores"
}
]
}