我正在尝试在我的微服务项目中生成一个 swagger,在 Api Gateway 中将所有服务 swagger 聚合为一个。为了实现这一点,我正在关注下一个教程https://objectpartners.com/2017/09/28/aggregate-services-into-a-single-swagger
这里的问题是,当我尝试设置绝对 URL 时,我收到的输出是无法加载 API 定义。undefined http://localhost:8070/apihttp://localhost:8081/api/v2/api-docs其中localhost:8070/api是 api 网关的基本 URL,而localhost:8081/api/v2/api- docs是微服务的 swagger 的 docs URL。
这是我的代码:
招摇配置
package com.rfd.apigateway.swagger;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.List;
@Configuration
@ConfigurationProperties(prefix = "swagger")
public class SwaggerConfiguration {
private List<Resource> resources;
public List<Resource> getResources() {
return resources;
}
public void setResources(List<Resource> resources) {
this.resources = resources;
}
}
资源
package com.rfd.apigateway.swagger;
public class Resource {
private String name;
private String url;
private String version;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
文档控制器
package com.rfd.apigateway.swagger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import java.util.ArrayList;
import java.util.List;
@Component
@Primary
@EnableAutoConfiguration
public class DocumentationController implements SwaggerResourcesProvider {
private SwaggerConfiguration swaggerConfiguration;
@Autowired
public DocumentationController(SwaggerConfiguration swaggerConfiguration){
this.swaggerConfiguration = swaggerConfiguration;
}
@Override
public List get() {
List resources = new ArrayList<>();
for(Resource resource : this.swaggerConfiguration.getResources()){
resources.add(createSwaggerResource(resource));
}
return resources;
}
private SwaggerResource createSwaggerResource(Resource resource) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(resource.getName());
swaggerResource.setUrl(resource.getUrl());
swaggerResource.setSwaggerVersion(resource.getVersion());
return swaggerResource;
}
}
最后,application.yml
swagger:
resources:
- name: transactions
url: http://localhost:8081/api/v2/api-docs
version: 1.0
- name: payments
url: http://localhost:8083/api/v2/api-docs
version: 1.0
还有一些可以帮助理解问题的图像: